AngularJs的MVC全部借助于$scope(作用域)实现
1.ng指令
<!doctype html> <html ng-app> <head> <meta charset="utf-8"> </head> <body> <div ng-controller="CommonController"> <div ng-controller="Controller1"> <p>{{greeting.text}},Angular</p> <button ng-click="test1()">test1</button> </div> <div ng-controller="Controller2"> <p>{{greeting.text}},Angular</p> <button ng-click="test2()">test2</button> <button ng-click="commonFn()">通用</button> </div> </div> </body> <script src="js/angular-1.3.0.js"></script> <script src="MVC3.js"></script> </html>
通过$scope获取对象
function CommonController($scope){ $scope.commonFn=function(){ alert("这里是通用功能!"); }; } function Controller1($scope) { $scope.greeting = { text: 'Hello1' }; $scope.test1=function(){ alert("test1"); }; } function Controller2($scope) { $scope.greeting = { text: 'Hello2' }; $scope.test2=function(){ alert("test2"); } }
2.实现Model
<!doctype html> <html ng-app> <head> <meta charset="utf-8"> </head> <body> <div> <input ng-model="greeting.text"/> <p>{{greeting.text}},Angular</p> </div> </body> <script src="js/angular-1.3.0.js"></script> </html>
1.ng-app规定了作用域为AngularJs解析 ng-model可以形成greeting.text模型对象
3.实现view
<!doctype html> <html ng-app="MyModule"> <head> <meta charset="utf-8"> </head> <body> <hello></hello> </body> <script src="js/angular-1.3.0.js"></script> <script src="HelloAngular_Directive.js"></script> </html>
通过Directive实现View的复用 <hello></hello>
var myModule = angular.module("MyModule", []); myModule.directive("hello", function() { return { restrict: 'E', template: '<div>Hi everyone!</div>', replace: true } });
$scope
- $scope是一个POJP(Plain Old JavaScript Object)
- $scope提供了一些工具方法$watch $apply
- $scope是表达式的执行环境(作用域)
- $scope是一个树型结构,与DOM标签平行
- 子$scope对象会继承父$scope上的属性和方法
- 每一个Angular应用只有一个根$scope对象(一般位于ng-app上)
- $scope可以传播事件,类似DOM事件,可以向上也可以向下
- $scope不仅是MVC的基础,也是后面实现双向数据绑定的基础
- 可以通过angular.element($0).scope()
- 调试插件:Inspect Angular Scope(chrome)
- 生命周期:Creation-Watcher registration-Model mutation-Mutation observation-Scope destruction