tips from angular.js wiki
Blogs20152015-07-14
The following are 2 tips from github.com/angular/angular.js/wiki, pretty helpful:
1. 4 scopes
There are four types of scopes:
- normal prototypal scope inheritance — ng-include, ng-switch, ng-controller, directive with `scope: true`
- normal prototypal scope inheritance with a copy/assignment — ng-repeat. Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property. The following example is from Mark Rajcok: each child scope still gets a new “item” property, but because list is now an array of objects, childScope[valueIdent] = value; results in the item property’s value being set to a reference to one of the array objects (not a copy).
- isolate scope — directive with scope: {…}. This one is not prototypal, but ’=’, ’@’, and ’&’ provide a mechanism to access parent scope properties, via attributes.
- transcluded scope — directive with transclude: true. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.
2. $apply range:
How to use $scope.$apply()? Here from angularjs wiki:
AngularJS provides wrappers for common native JS async behaviors:
- Events => ng-click
- Timeouts => $timeout
- jQuery.ajax() => $http
This is just a traditional async function with a $scope.$apply() called at the end, to tell AngularJS that an asynchronous event just occurred.
**$scope.$apply() should occur as close to the async event binding as possible.**
Do NOT randomly sprinkle it throughout your code. If you are doing:
if (!$scope.$$phase) $scope.$apply() it’s because you are not high enough in the call stack.
Whenever possible, use AngularJS services instead of native. If you’re creating an AngularJS service (such as for sockets) it should have a $scope.$apply() anywhere it fires a callback.