Sunday, October 11, 2015

AngularJS Misc




$http.get('path/to/service', {timeout: 5000});

   var _date = $filter('date')(new Date(input), 'MMM dd yyyy');

{{ d.time | date }}
http://www.ericluwj.com/2015/11/06/angularui-ui-bootstrap-datepicker-and-timepicker-neutral-timezone.html
https://github.com/thoughtbot/guides/tree/master/best-practices
  • Avoid manual dependency annotations. Disable mangling or use a pre-processor for annotations.
  • Prefer factory to service. If you desire a singleton, wrap the singleton class in a factory function and return a new instance of that class from the factory.
  • Prefer the translate directive to the translate filter for performance reasons.
  • Don't use the jQuery or $ global. Access jQuery via angular.element.
https://github.com/danialfarid/ng-file-upload/issues/178
Adding new parameters in upload method
If they need to be "parameters"... as in, query parameters (page?key=val&key2=val2), pass through a params object:
$scope.upload = $upload.upload({
    url: 'UploadTest/upload',
    params: {
        key: val,
        key2: val2
    }

http://blog.ionic.io/angularjs-console/
> angular.element(targetNode).scope()

> angular.element(targetNode).isolateScope()

Where targetNode is a reference to an HTML Node. You can grab one easily using document.querySelector().
We can grab a reference to any service using the injector function of element where ngApp was defined, or indirectly though any element with theng-scope class:
> angular.element(document.querySelector('html')).injector().get('MyService')
We can then call methods on that service just like we could if we injected it.
> angular.element('my-pages').controller()

  • $0 – $4: Access the last 5 DOM elements selected in the inspector window. This is convenient for grabbing scopes for selected elements:angular.element($0).scope()
  • $(selector) and $$(selector): A quick replacement for querySelector() andquerySelectorAll, respectively.
TODO: http://juristr.com/blog/2016/02/debugging-angular2-console/

http://juristr.com/blog/2015/12/perf-startup-ng1/
return gulp.src('dist/app/app.js')
.pipe(insert.prepend("window.prod = true;\n")) 
.pipe(insert.prepend(cacheBust)).pipe(gulp.dest('dist/app'));
angular .module('myApp', []) .config(function($logProvider, $compileProvider) { if (window.prod) { $logProvider.debugEnabled(false); $compileProvider.debugInfoEnabled(false); } });
http://juristr.com/blog/2014/11/learning-ng-angularjs-utility-functions/
the directives don't create a separate, isolated scope and thus, the vm variable of the directive controller on<second-directive> overwrites the vm variable of the directive controller on <first-directive>. Thus, two times "Hello World".
Directive controllers don't create a separate scope out of the box!
Interestingly, while a normal controller creates a scope, the directive controller doesn't do so. It totally makes sense, but you might easily fall into this trap.
Angular nicely marks the scope with the ng-scope class. 
Directives can be forced to create an isolated scope. This is done by using the scope property, in the simplest case by setting it to true.
.directive('firstDirective', function() {
    return {
      restrict: 'E', scope:true,
      template: '<div>First directive: {{ vm.msg }}</div>',
      controller: function() {
        var vm = this;
        vm.msg = 'Hi';
      },
      controllerAs: 'vm'
    }; 
})The scope variable can either have true or false (default) as we've just seen, or you pass an object explicitly specifying which properties should be passed from outside into the directive (basically for configuring it).
angular.directive('myDirective', function(){
  return {
    ...
    scope: {
      obj1: '=',
      obj2: '@',
      obj3: '&'
    }
    ...
  };
});
= stands for data binding, it passes a reference to an object inside your directive. It keeps the expression in the attribute in sync with the isolated scope, thus allows for 2-way bindings.
<my-directive obj1="vm.someObject"></my-directive>
@ stands for interpolation. It is used with {{}} and will always return a string.
<my-directive ob1="{{ vm.msg }}"></my-directive>
& stands for expression. Within the directive it will be made available as a function, that, when called, executes the passed expression. Use it like
<my directive callback="vm.showAlert('Hi')"></my-directive>
..with your directive configuration object being defined for instance like this:
return {
    ...
    scope: {
        callback: '&'
    },
    template: '<button ng-click="callback()">Click</button>'
    ...
}

Learning AngularJS
https://github.com/bwdbooks/learning-angularjs
Modules
The module provides a namespace that enables you to reference directives, scopes, and other components based on model name. This makes it easier to package and reuse parts of an application.

Each view or web page in AngularJS has a single module assigned to it via the ng-app directive. However, you can add other modules to the main module as dependencies, which provides a very structured and componentized application.

Scopes and the Data Model
AngularJS introduces the concept of a scope. A scope is really just a JavaScript representation of data used to populate a view presented on a web page.

you can nest scopes to organize your data to match the context that they are being used in.
Most dynamic web applications use direct JavaScript or a JavaScript-based library such as jQuery to manipulate a DOM object to change the behavior and appearance of the rendered HTML element in the user view.

AngularJS introduces a new concept of combining templates that contain directives which extend the HTML tags and attributes directly with JavaScript code in the background to extend the capability of HTML. Directives have two parts. The first part is extra attributes, elements, and CSS classes that are added to an HTML template. The second part is JavaScript code that extends the normal behavior of the DOM.

you should use your own custom directives to do any direct DOM manipulation that a web application needs.

Controllers augment the scope by setting up the initial state or values in the scope and by adding behavior to the scope.

Data Binding
In AngularJS data binding is a two-way process: When data is changed on a web page, the model is updated, and when data is changed in the model, the web page is automatically updated. This way, the model is always the only source for data represented to the user, and the view is just a projection of the model.

Services
Services are the major workhorses in the AngularJS environment. Services are singleton objects that provide functionality for a web app.

Dependency Injection
Dependency injection is a process in which a code component defines dependencies on other components. When the code is initialized, the dependent component is made available for access within the component.

Compiler
AngularJS provides an HTML complier that will discover directives in the AngularJS template and use the JavaScript directive code to build out extended HTML elements. The AngularJS compiler is loaded into the browser when the AngularJS library is bootstrapped. When loaded, the compiler will search through the HTML DOM in the browser and link in any back-end JavaScript code to the HTML elements, and then the final application view will be rendered to the user.

THE ANGULARJS LIFE CYCLE
bootstrap
This occurs when the AngularJS JavaScript library is downloaded to the browser. AngularJS initializes its own necessary components and then initializes your module, which the ng-app directive points to. The module is loaded, and any dependencies are injected into your module and made available to code within the module.

compilation
During the compilation phase, the static DOM is replaced with a dynamic DOM that represents the AngularJS view.

This phase involves two parts: traversing the static DOM and collecting all the directives and then linking the directives to the appropriate JavaScript functionality in the AngularJS built-in library or custom directive code. The directives are combined with a scope to produce the dynamic or live view.

runtime
AngularJS behaves differently from traditional methods of binding data. Traditional methods combine a template with data received from the engine and then manipulate the DOM each time the data changes. AngularJS compiles the DOM only once and then links the compiled template as necessary, making it much more efficient than traditional methods.

SEPARATION OF RESPONSIBILITIES
■ If you need to perform any DOM manipulation, do it in a built-in or your own custom directive JavaScript code—and nowhere else.
■ Implement any reusable tasks as services and add them to your modules by using dependency injection.
■ Ensure that the scope reflects the current state of the model and is the single source for data consumed by the view.
■ Ensure that the controller code only acts to augment the scope data and doesn’t include any business logic.
■ Define controllers within the module namespace and not globally. This ensures that your application can be packaged easily and prevents overwhelming the global namespace.

you should include the angular.js library as one of the last tags, if not the last tag, inside the <body> of the HTML. When the angular.js script is loaded, the compiler kicks off and begins searching for directives. Loading angular.js last allows the web page to load faster.

angular.element will be an alias for the jQuery variable
angular.element() === jQuery() === $()

All element references in AngularJS are always wrapped as jQuery or jQuery lite objects
use the angular.element() method to convert the target DOM object into a jQuery object.
$scope.clicked = function(event){
  var jQueryElement = angular.element(event.target);
};

AngularJS is built on the module principle. Most of the functionality provided by AngularJS is built into a module named ng

If you do not specify a requires parameter, then instead of a Module object being created, the already-created instance is returned
var myModule3 = angular.module('myModule');

■ controller(name, controllerFactory)
AngularJS has a built-in controller object and knows that all controller objects must receive a scope object as the first parameter.
■ factory(name, factoryFunction): This method uses the factoryFunction parameter to build an object that will be provided by the injector.

Scope not only provides the data represented in a model but also binds together all the other components of the AngularJS application, such as modules, controllers, services, and templates.

The root scope stores data at the application level, and you can access it by using the $rootScope service.

Access data from the database or other back-end sources via AngularJS services
Ensure that data read from the server updates the scope, which in turn updates the view.

The Scope Life Cycle
1. Creation
The creation phase occurs when a scope is initialized. Bootstrapping the application creates a root scope. Linking the template creates child scopes when ng-controller or ng-repeat directives are encountered.

The digest loop is responsible for updating DOM elements with changes made to the model, as well as executing any registered watcher functions.
2. Watcher registration
The watcher registration phase registers watches for values in the scope that are represented in the template. These watches propagate model changes automatically to the DOM elements.

You can also register your own watch functions on a scope value by using the $watch() method. This method accepts a scope property name as the first parameter and then a callback function as the second parameter. The old and new values are passed to the callback function when the property is changed in the scope.

3. Model mutation
The model mutation phase occurs when data in the scope changes. When you make changes in your AngularJS code, a scope function called $apply() updates the model and calls the $digest() function to update the DOM and watches.

4. Mutation observation

5. Scope destruction
The $destroy() method removes scopes from the browser memory. The AngularJS libraries automatically call this method when child scopes are no longer needed. The $destroy() method stops $digest() calls and removes watches, allowing the memory to be reclaimed by the browser garbage collector.

IMPLEMENTING SCOPE HIERARCHY
Scopes are organized into hierarchies, and the root scope is defined at that application level. Each instance of a controller also gets an instance of a child scope. From the child scopes you can access data that is stored in the parent scope hierarchy.

AngularJS template
During compilation, HTML tags and attributes are normalized to support the fact that AngularJS is case-sensitive, whereas HTML is not. Normalization does two things:
■ Strips the x- and data- prefixes from the front of elements and attributes.
■ Convert names with : or - or _ to camelCase.

■ More forgiving: Expressions do not throw exceptions when they encounter undefined or null variable types; instead, they treat these as having no value.

ng-click="removedArr.push(myArr.shift())"
{{myArr.length}}
15     $scope.setSort = function(column){
16       $scope.column = column;
17       $scope.reverse = !$scope.reverse;
18     };

18         <th ng-click="setSort('make')">Make</th>
19         <th ng-click="setSort('model')">Model</th>
20         <th ng-click="setSort('capacity')">Capacity</th>
       <tr ng-repeat=
           "plane in filteredPlanes | orderBy:column:reverse">

Directives are a combination of AngularJS template markups and supporting JavaScript code. AngularJS directive markups can be HTML attributes, element names, or CSS classes. The JavaScript directive code defines the template data and behavior of the HTML elements.

  directive('myDirective', function() {
    return {
      template: 'Name: {{name}} Score: {{score}}'
    };
Adding a Controller to a Directive

The require option uses the require:'^controller' syntax to instruct the injector service to look in parent contexts until it finds the controller.
directive('myDirective', function() {
  return {
    scope: {title: '='},
    controller: function ($scope){
      $scope.title = "new";
      $scope.myFunction = function(){
      });
    }
  };
});
Adding an Inherited Scope
    scope: true
Adding an Isolate Scope
    scope: { },
■ @: Binds a local scope string to the value of the DOM attribute. The value of the attribute will be available inside the directive scope.
■ =: Creates a bidirectional binding between the local scope property and the directive scope property.
■ &: Binds a function in the local scope to the directive scope.
      scope: {title: '=', newFunc:"&myFunc", info: '@'},
      template: '<div ng-click="newFunc()">{{title}}: {{info}}</div>'
title: '@' is the same as title: '@title'
<div my-directive
     my-func="myFunc()"
     title="title"
     info="SomeString"></div>
if you want to use the functionality in more than one place and definitely if you will reuse it in multiple applications, you should define a custom directive that implements the handlers.

ADDING $WATCHES TO TRACK SCOPE CHANGE EVENTS
$scope.score = 0;
$scope.$watch('score', function(newValue, oldValue) {
  if(newValue > 10){
    $scope.status = 'win';
  }
});
Using $watchGroup to Track Multiple Scope Variables
$scope.$watchGroup(['score', 'time'], function(newValues, oldValues) {
  if(newValues[0] > 10){
    $scope.status = 'win';
  } else if (newValues[1] > 5{
    $scope.status = 'times up';
});
25   $scope.$watchCollection('myObj', function (newValue, oldValue){
26     $scope.changes += 1;
27   });

Emitting a Custom Event to the Parent Scope Hierarchy
Broadcasting a Custom Event to the Child Scope Hierarchy
Handling Custom Events with a Listener
scope.$on(name, listener)

$http for web server communication, $cookieStore for storing and retrieving browser cookies, and $animate to provide animation capabilities. $cacheFactory
app.controller('myController', ['$scope', '$window',
                                function($scope, window) {
    window.alert("Your Screen is: \n" +
        window.screen.availWidth + "X" + window.screen.availHeight);
  }]);
var cookie = $cookies.appCookie;
$cookies.appCookie = 'New Value';

you load the angular-cookies.js library in the template after angular.js but before application.js.
you add ngCookies to the required list in your application Module definition.
var app = angular.module('myApp', ['ngCookies']);

app.controller('myController', ['$scope', '$cookieStore',
                                function($scope, cookieStore) {
}]);

When you call the $interval() and $timeout() methods, they return a promise object that you can use to cancel the timeout or interval.
var myInterval = $interval(function(){$scope.seconds++;}, 1000, 10, true);

If you create timeouts or intervals by using $timeout or $interval, you must explicitly destroy them by using cancel() when the scope or elements directives are destroyed.
$scope.$on('$destroy', function(){
  $scope.cancel(myInterval);
});


var deferred = $q.defer();
app.value('myValue', {color:'blue', value:'17'});

var app = angular.module('myApp', []);
app.constant('myConst', 10);
app.factory('multiplier', ['myConst', function (myConst) {
  return function(value) { return value + myConst; };
}]);

Beginning AngularJS
Filters
{{data.consumption | number }}
{{ data.dateJoined | date:'medium'}
    <li ng-repeat="gigabytes in data.monthlyUsageHistory | limitTo:5">
        {{ gigabytes | number:2}}
    </li>
<li ng-repeat="gb in data.monthlyUsageHistory | limitTo:-3"> -- last 3 items

Modules
A module is a collection of controllers, directives, filters, services, and other configuration information.

var myAppModule = angular.module('myAppModule', []); // This can be used to pass a list of dependencies; that is, other modules that this module depends upon.

Bootstrapping AngularJS
<html ng-app="myAppModule">
<script src="js/myAppModule.js"></script>
<body ng-controller="MyFilterDemoCtrl">
myAppModule.filter('stripDashes', function () { .. });

Directives
<div ng-controller="myFilterDemoCtrl"></div>
<div data:ng-controller="myFilterDemoCtrl"></div>
<button ng-click="showHideColors()" type="button">
    {{isHidden ? 'Show Available Colors' : 'Hide Available Colors'}}
</button>
<div id="red" ng-hide="isHidden">Red</div>
<span ng-bind="2+2"></span> ==> {{2+2}}
if a document takes some time to load, your HTML page might temporarily show the raw expressions to your end users. That is to say, they may literally see the {{2+2}} appear momentarily before Angular JS gets a chance to compile it and show the desired values. Using ngBind does not have this unfortunate side effect.

ngCloak
<p ng-cloak>{{ 2 + 2 }}</p>
The cloaking of the expression happens because ngCloak applies a CSS rule that hides it, although it is only hidden until Angular JS has determined that it can display the evaluated value.
it is often better to apply it on individual elements.

<div ng-include="'include-me.html'"></div>
<div ng-repeat="city in ['Liverpool','Perth','Sydney','Dublin','Paris']">
Event-Handling Directives

Creating a Custom Directive
     <div color-list colors="colorsArray"></div>
myAppModule.directive('colorList', function () {

    return {

        restrict: 'AE',
        template:
              "<button ng-click='showHideColors()' type='button'>"
            + "{{isHidden ? 'Show Available Colors' : 'Hide Available Colors'}}"
            + "</button><div ng-hide='isHidden' id='colorContainer'>"
            + "</div>"

        }
});
The restrict option is used to specify how a directive can be invoked.

<input type="text" name="firstName" ng-model="person.firstName"/><br/>
if(angular.isDefined($scope.firstName)){
<input type="email" placeholder="Email" name="email" ng-model="person.email" required>
<select name="channels" ng-model="person.channels">
<option value="">Where did you hear about us?</option>
</select>

<form name="registrationForm" ng-submit="person.register()" novalidate>
<input type="text" placeholder="First Name" name="firstName" ng-model="person.firstName" required>
  if(!$scope.registrationForm.firstName.$valid){
    $scope.firstNameInvalid = true;
  }
Services and Server Communication
The $window service is essentially a reference to the browser’s window object.
module.controller("MyController", function ($scope, $window) {
    $scope.winWidth = $window.innerWidth;
});

$location
The $location service will not cause a full-page reload when the browser URL is changed. In order to achieve this, you should use the $window.location.href property.
$document
$http and $animation
The $window service offers us the benefit of abstraction;
services are implemented as singletons, which are objects that are instantiated only once per application.

        module.factory('dateTimeService', function () {

            var dateTimeSvc = {};
            dateTimeSvc.getDate = function () {
                return new Date().toDateString();
            }

            dateTimeSvc.getTime = function () {
                return new Date().toTimeString();
            }

            return  dateTimeSvc;

        }).controller("MyController", function ($scope, dateTimeService) {

            $scope.theDate = dateTimeService.getDate();
            $scope.theTime = dateTimeService.getTime();

        });
The second argument is the factory function, which returns an object. This object is known as the service object, and it represents the service that you will ultimately use in your application.

a promise represents a value that may not be available yet, but one that will be resolved at some point in future. This value is usually the outcome of an asynchronous task such as an Ajax call to a remote server.

$http service allows you to communicate with a web server via the browser’s XMLHttpRequest object.
module.factory('memberDataStoreService', function ($http) {

var memberDataStore = {};

memberDataStore.doRegistration = function (theData) {
                    var promise = $http({method: 'POST', url: 'memberservices/register', data: theData});
        return promise;
}

return  memberDataStore;
});

<input ng-disabled="working" type="submit" value="Register"/>
<span ng-show="working" style="padding-left:10px;">
    <img src="images/loading.gif"/>
</span>

if ($scope.registrationForm.$valid) {

    $scope.working = true;
    var promise = memberDataStoreService.doRegistration($scope.person);

    promise.success(function (data, status) {
        $scope.showSuccessMessage = true;
    });

    promise.error(function (data, status) {
        $scope.showErrorMessage = true;
    });

    promise.finally(function () {
        $scope.working = false;
    });

    $scope.doShow = true;
}

ngRoute
$route service allows you to create a set of mappings between URLs and view file names.
        var app = angular.module('app', ['ngRoute']);
        app.config(function ($routeProvider) {

            // configure the routes
            $routeProvider

                    .when('/', {
                      // route for the home page
                        templateUrl: 'pages/home.html',
                         controller: 'homeController'
                    })'
we declared a dependency on the ngRoute module
Providers are objects that create instances of services and expose configuration APIs. You need to use $routeProvider within the config() method.

    .when('/contact/:subject', {
        templateUrl: 'pages/contact.html',
        controller: 'contactController'
    });
if ($routeParams ['subject'] == "learn") {
    subject = 'I want to learn more about your services';
} else if ($routeParams ['subject'] == "quote") {
    subject = 'I would like to get a free quote';
}
Eager vs. Conservative Routes
when('/product/:id/:size/:color/:fit', {
when('/product/:id/:data*', {

 
Features
https://www.quora.com/What-are-the-advantages-of-using-AngularJS-over-JQuery
http://code.tutsplus.com/tutorials/5-awesome-angularjs-features--net-25651
http://anandmanisankar.com/posts/angularjs-best-parts/
Two way data binding
The data-binding directives provide a projection of your model to the application view.
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<body ng-app="SampleMVCApp"> <div ng-controller="SampleController"> <h2>{{getText()}}</h2> </div> </body> angular.module("SampleMVCApp", []) .controller("SampleController", function ($scope) { $scope.getText = function(){ return "Howzzaaatttt!"; }; });

Templates
MVW pattern (similar to MVC)
The Model
The model is simply the data in the application. The model is just plain old JavaScript objects.

The ViewModel
A viewmodel is an object that provides specific data and methods to maintain specific views.

The viewmodel is the $scope object that lives within the AngularJS application. $scope is just a simple JavaScript object with a small API designed to detect and broadcast changes to its state.

The Controller
The controller is responsible for setting initial state and augmenting $scope with methods to control behavior. It is worth noting that the controller does not store state and does not interact with remote services.

The View

The $scope has a reference to the data, the controller defines behavior, and the view handles the layout and handing off interaction to the controller to respond accordingly.

Feature 4: Dependency Injection
Dependency Injection (DI) allows you to ask for your dependencies, rather than having to go look for them or make them yourself.
To gain access to core AngularJS services, it is simply a matter of adding that service as a parameter; AngularJS will detect that you need that service and provide an instance for you.

  function EditCtrl($scope, $location, $routeParams) {
       // Something clever here...
  }
You are also able to define your own custom services and make those available for injection as well.

Feature 5: Directives

Full testing environment
Communication with server
Deep-Linking
Deep Linking for dynamic pages
Reusable components and localization to name a few

http://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
app.service('MyService', function () {
  this.sayHello = function () {
    console.log('hello');
  };
});
.service() is a method on our module that takes a name and a function that defines the service. Pretty straight forward. Once defined, we can inject and use that particular service in other components, like controllers, directives and filters, like this:
app.controller('AppController', function (MyService) {
  MyService.sayHello(); // logs 'hello'
});

class MyService {
  sayHello() {
    console.log('hello');
  }
}

app.service('MyService', MyService);

http://stackoverflow.com/questions/13181406/angularjs-http-and-resource
$http makes general purpose AJAX call, in which general means it can include RESTful api plusNon-RESTful api.
and $resource is specialized for that RESTufl part.
Restful Api came to prevalent in recent years because the url is better organized instead of random url made up by programmers.
If I use a RESTFul API to construct the url, it would be something like /api/cars/:carId.
$reserouce way to fetch data
angular.module('myApp', ['ngResource'])

    // Service
    .factory('FooService', ['$resource', function($resource) {
        return $resource('/api/cars/:carId')
    }]);

    // Controller
    .controller('MainController', ['FooService', function(FooService){
        var self = this;
        self.cars = FooService.query();
        self.myCar = FooService.get('123');

    }]);
This will give you an resource object, which is companied with getsavequeryremovedelete methods automatically.
$http way to fetch data
angular.module('myAp', [])

    // Service
    .factory('FooService', ['$http', function($http){
        return {
            query: function(){
                return $http.get('/api/cars');
            },

            get: function(){
                return $http.get('/api/cars/123');
            }
            // etc...
        }
https://docs.angularjs.org/api/ng/directive/ngOpen


angular.module('myApp', [])
.controller('Ctrl', function($scope, MyFactory) {
  $scope.data = MyFactory.getPlayer();
  $scope.update = MyFactory.swapPlayer;
})
.factory('MyFactory', function() {
  // private variables and functions
  var player = {
    name: 'Peyton Manning',
    number: 18
  },  swap = function() {
    player.name = 'A.J. Green';
  };
  // public API
  return {
    getPlayer: function() {
      return player;
    },
    swapPlayer: function() {
      swap();
    }
  };
});

angular.module('myApp', [])
.controller('Ctrl', function($scope, MyService) {
  $scope.data = MyService.getPlayer();
  $scope.update = MyService.swapPlayer;
})
.service('MyService', function() {
  var player = {
    name: 'Philip Rivers',
    number: 17
  },  swap = function() {
    player.name = 'Alshon Jeffery';
  };
  this.getPlayer = function() {
    return player;
  };
  this.swapPlayer = function() {
    swap();
  };
});

https://github.com/mgechev/angularjs-style-guide


Keep things simple and put AngularJS specific directives after standard attributes. This will make it easier to skim your code and will make it easier to maintain because your attributes are consistently grouped and positioned.
ElementNaming styleExampleusage
ModuleslowerCamelCaseangularApp
ControllersFunctionality + 'Ctrl'AdminCtrl
DirectiveslowerCamelCaseuserInfo
FilterslowerCamelCaseuserFilter
ServicesUpperCamelCaseUserconstructor
ServiceslowerCamelCasedataFactoryothers
  • Do not use JQUERY inside your app, If you must, use JQLite instead with angular.element.
  • When resolving dependencies through the DI mechanism of AngularJS, sort the dependencies by their type - the built-in AngularJS dependencies should be first, followed by your custom ones:
module.factory('Service', function ($rootScope, $timeout, MyCustomDependency1, MyCustomDependency2) {
  return {
    //Something
  };
});
  • Why business logic / app state inside controllers is bad?
    • Controllers instantiated for each view and dies when the view unloads
    • Controllers are not reusable - they are coupled with the view
    • Controllers are not meant to be injected
https://google.github.io/styleguide/angularjs-google-style.html

http://stackoverflow.com/questions/22898927/injecting-scope-into-an-angular-service-function
The $scope that you see being injected into controllers is not some service (like the rest of the injectable stuff), but is a Scope object. Many scope objects can be created (usually prototypically inheriting from a parent scope). The root of all scopes is the $rootScope and you can create a new child-scope using the $new() method of any scope (including the $rootScope).
The purpose of a Scope is to "glue together" the presentation and the business logic of your app. It does not make much sense to pass a $scope into a service.
Services are singleton objects used (among other things) to share data (e.g. among several controllers) and generally encapsulate reusable pieces of code (since they can be injected and offer their "services" in any part of your app that needs them: controllers, directives, filters, other services etc).
http://thecodebarbarian.com/2015/01/24/angularjs-interceptors
var m = angular.module('myApp', []);

m.config(function($httpProvider) {
  $httpProvider.interceptors.push(function() {
    return {
      response: function(res) {
        /* This is the code that transforms the response. `res.data` is the
         * response body */
        res.data = { data: data };
        res.data.meta = { status: res.status };
        return res;
      }
    };
  });
});
This simple HTTP interceptor demonstrates the basic interceptor syntax. Interceptors are represented as an array of functions on the $httpProvider provider. Providers can only be accessed in config() blocks, so you must define your interceptors in a call to app.config(). The interceptor function must return a JSON map which can contain any of the following 4 keys:
  • request
  • response
  • requestError
  • responseError
The response property should be a function that takes a single parameter, the res object, and returns a response object. The above example modifies the res object and returns it, but you can return a completely new object if you need to. 
The primary use case for interceptors in practice involves request interceptors and authentication
Request Interceptors: Setting the Authorization Header
Suppose userService looks like this:
var m = angular.module('myApp', []);

m.factory('userService', function() {
  return {
    getAuthorization: function() {
      return 'Taco';
    }
  }
});
How are you going to tie this service into an interceptor? It's easier than you think: the interceptor function is tied in to the AngularJS dependency injector.
m.config(function($httpProvider) {
  // Pull in `userService` from the dependency injector
  $httpProvider.interceptors.push(function(userService) {
    return {
      request: function(req) {
        // Set the `Authorization` header for every outgoing HTTP request
        req.headers.Authorization =
          userService.getAuthorization();
        return req;
      }
    };
  }
});
Thanks to this request interceptor, all your outgoing HTTP requests now have an Authorization header. 
Error Interceptors: Fun with Promises
m.config(function($httpProvider) {
  $httpProvider.interceptors.push(function($q, $injector, userService) {
    return {
      request: function(request) {
        request.headers.authorization =
          userService.getAuthorization();
        return request;
      },
      // This is the responseError interceptor
      responseError: function(rejection) {
        if (rejection.status === 401) {
          // Return a new promise
          return userService.authenticate().then(function() {
            return $injector.get('$http')(rejection.config);
          });
        }

        /* If not a 401, do nothing with this error.
         * This is necessary to make a `responseError`
         * interceptor a no-op. */
        return $q.reject(rejection);
      }
    };
  });
});
The above code assumes the userService.authenticate() function returns a then()-able promise around the user entering their password. If that condition is met, the above interceptor is sufficient to gracefully handle session timeouts. If the server returns an HTTP 401, this interceptor will prompt the user to log in and return a new promise. This new promise wraps the user logging in and the$injector.get('$http')(rejection.config) call, which is responsible for retrying the HTTP request. Thanks to the magic of promises, the returned promise resolves if and only if the user authenticates and the retried HTTP call succeeds.
var authenticate = function() {
  var $modal = $injector.get('$modal');

  var modal = $modal.open({
    template: '<div style="padding: 15px">' +
              '  <input type="password" ng-model="pwd">' +
              '  <button ng-click="submit(pwd)">' +
              '    Submit' +
              '  </button>' +
              '</div>',
    controller: function($scope, $modalInstance) {
      $scope.submit = function(pwd) {
        $modalInstance.close(pwd);
      };
    }
  });

  /* `modal.result` is a promise that gets resolved when 
   * $modalInstance.close() is called */
  return modal.result.then(function(pwd) {
    password = pwd;
  });
};
The general high-level structure of an AngularJS application looks like this: controllers handle making the data accessible from a given scope, directives handle the visual rules for displaying and interacting with the data, and filters help directives format the data.

app.filter('displayName', function() {

  return function(name) {

    return name.first + " " + name.last;

  }
});
{{user.name | displayName | limitTo:40}}
angular.
  module('myApp', []).
  filter('pluralize', function() {
    return function(ordinal, noun) {
      if (ordinal == 1) {
        return ordinal + ' ' + noun;
      } else {
        var plural = noun;
        if (noun.substr(noun.length - 2) == 'us') {
          plural = plural.substr(0, plural.length - 2) + 'i';
        } else if (noun.substr(noun.length - 2) == 'ch' || noun.charAt(noun.length - 1) == 'x' || noun.charAt(noun.length - 1) == 's') {
          plural += 'es';
        } else if (noun.charAt(noun.length - 1) == 'y' && ['a','e','i','o','u'].indexOf(noun.charAt(noun.length - 2)) == -1) {
          plural = plural.substr(0, plural.length - 1) + 'ies';
        } else if (noun.substr(noun.length - 2) == 'is') {
          plural = plural.substr(0, plural.length - 2) + 'es';
        } else {
          plural += 's';
        }
        return ordinal + ' ' + plural;
      }
    };
  });
I’ve visited {{3 | pluralize:’city’}} // I’ve visited 3 cities
<a ng-href="/product/{{product.id}}?from={{encodeURIComponent('/products')}}">Go To Individual Product Page</a>
This is because AngularJS expressions don’t by default have access to the window object, i.e. the global scope of the page where encodeURIComponent lives, unless you inject $window into your controller and explicitly make it accessible from the controller’s scope. However, doing this for every single controller is a really bad idea, so the slightly more correct way of making encodeURIComponent accessible from an expression is a filter:
1
2
3
4
5
filter('encodeUri', function() {
  return function(x) {
    return encodeURIComponent(x);
};
});
1
<a ng-href="/product/{{product.id}}?from={{'/products' | encodeUri}}">

    <select ng-model="countryToShip" ng-options="country.name for country in countries | orderBy:'name' | hardcodeFirst:'name':'United States'"></select>
https://thecodebarbarian.wordpress.com/2013/05/12/how-to-easily-validate-any-form-ever-using-angularjs/


http://angular-ui.github.io/bootstrap/#/modal

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts