Sunday, November 9, 2014

more AngularJS details

AngularJS scope and watch

1) $scope.$watch(VAR, CALLBACK)
2) $scope.$apply() - notify about changes
3) AngularJS scopes are organized in a tree structure and a scope can access its ancestor’s variables. Well, this means that $digest() needs to happen on every child scope in every iteration! Internally, this code is a bit messy in AngularJS, but each iteration of the $digest() loop does a depth-first search and performs the watcher check on every child scope. If any child scope is dirty, the loop has to run again!
4) UI is blocked while $digest() is running
5) angular.equals(A, B) - internal angular function for comparing

AngularJS UI router 

https://github.com/angular-ui/ui-router

1) templateUrl param can return

  • url depending on $scope or $stateParams;
  • HTML of the template

$stateProvider.state('contacts', { templateUrl: function ($stateParams){ return '/partials/contacts.' + $stateParams.filterBy + '.html'; } })

2) Warning: The controller will not be instantiated if template is not defined.
3) Controllers can use the $scope.$on() method to listen for events fired by state transitions.
4) There is data param to attach custom data to states. Then accessible by -$state.current.data.customData1

5) You can resolve whole requests:
// Example using function with returned promise. // This is the typical use case of resolve. // You need to inject any services that you are // using, e.g. $http in this example promiseObj: function($http){ // $http returns a promise for the url data return $http({method: 'GET', url: '/someUrl'}); }, // Another promise example. If you need to do some // processing of the result, use .then, and your // promise is chained in for free. This is another // typical use case of resolve. promiseObj2: function($http){ return $http({method: 'GET', url: '/someUrl'}) .then (function (data) { return doSomeStuffFirst(data); }); },

+

1) ASYNCHRONOUS EVENTS
// in some service
$rootScope.$broadcast(MARIO_LOADED, { mario: data}); // when data loads
// in some controller
$scope.$on(MARIO_LOADED, doStuffWithMario);

2) RESTRICT
"E": Element, <my-directive>
"A": Attribute, <div my-directive>
"C": Class, <div class="my-directive">
And combinations of the above, e.g. "EA"

Link on a good presentation with some details