Things I Wish I Were Told About Angular.js 小记
Things I need to master:
1. understand modules
2. When controller get bigger, learn $scope:
how scope work
①$scope.watch() && $scope.apply()
②how the $scope is shared between controller and its child
③when AG will implicitly create a new $scope
④How the events ($scope.$on, $scope.$emit, $scope.$broadcast work as a communication among scopes)
3. when you manipulate DOM(view) in controller, write Directive
put control logic in directive controller, and DOM logic in link function; scope sharing is the glue.
4. AG router:
Angular.js works like server-side router: it is built to work with ng-view. When a route is hit, a template is loaded and injected into ng-view and some controller can be instantiated.
Some important Notes:
最后载入可以加速
<html ng-app>
<body>
...
<script src="angular.js"></script>
</body>
</html>
The basic startup flow looks like this:
1. A user requests the first page of your application.
2. The user’s browser makes an HTTP connection to your server and loads the in dex.html page containing your template.
3. Angular loads into the page, waits for the page to be fully loaded, and then looks for ng-app to define its template boundaries.
4. Angular traverses the template and looks for directives and bindings. This results in registration of listeners and DOM manipulation, as well as fetching initial data from the server. The end result of this work is that the app is bootstrapped and the template is converted into view as a DOM.
5. You connect to your server to load additional data you need to show the user as needed.
Dot
<div ng-app="">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
<div ng-controller="FirstCtrl">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
</div>
<div ng-controller="SecondCtrl">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
</div>
</div>
这里data.message都属于app的scope,same instance
但若replace "data.message" with just "message", it will break the inheritance that was bound all data.message.
每个message将会创建新的instance,数据将会各自不同!
Dependence Injection is order-independent:
function ShoppingController($scope, Items) {...}
function ShoppingController(Items, $scope) {...}
一样的
但是如果用array定义了注入顺序,那么就要按顺序
angular.module('myapp', ['myapp2'])
.controller('InvoiceController', ['$scope', 'currencyConverter', function($scope, currencyConverter) {
this.message = currencyConverter
$scope.message = currencyConverter
}]);
Define Service, there are 3 functions:
provider(name, ObjectOR constructor() )
factory(name, $getFunction() )
service(name, constructor() )