为什么需要MVC?
a. 代码规模越来越大,切分职责是大势所趋;
b. 为了复用:很多逻辑都是一样的;
c. 为了后期维护方便:修改一块功能不影响其他功能;
d. MVC只是手段,终极目标是模块化和复用!!!
AngularJS的MVC是借助于$scope实现的!!!
Controller实现方式
a. 方式一无法适应大型应用
b. 方式二无法实现复用
c. 方式三,不应该采用继承通用控制器这种方式,而应该将通用的控制模块封装成Service,然后让控制器调用它,而不是继承!
i. 错误的实现方式:
commonFn方法只要在CommonController中任意位置都可以被调用!!!
1) MVC3.html<!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>
2) MVC.js
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"); } }
Controller使用过程中的注意点:
a. 第五点,相互调用是一种非常强的耦合!Module
a. 通过$scope实现
b. MVC4.html<!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>
View
a. 使用Directive实现View的复用Scope
a. 简介:
b. 声明周期
c. scope的事件机制
i. Scope2.html<!doctype html> <html ng-app> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="Scope1.css" /> </head> <body> <div ng-controller="EventController"> Root scope <tt>MyEvent</tt> count: {{count}} <ul> <li ng-repeat="i in [1]" ng-controller="EventController"> <button ng-click="$emit('MyEvent')"> $emit('MyEvent') </button> <button ng-click="$broadcast('MyEvent')"> $broadcast('MyEvent') </button> <br> Middle scope <tt>MyEvent</tt> count: {{count}} <ul> <li ng-repeat="item in [1, 2]" ng-controller="EventController"> Leaf scope <tt>MyEvent</tt> count: {{count}} </li> </ul> </li> </ul> </div> </body> <script src="js/angular-1.3.0.js"></script> <script src="Scope2.js"></script> </html>
ii. Scope.js
function EventController($scope) { $scope.count = 0; $scope.$on('MyEvent', function() { $scope.count++; }); }
自己创建的变量不要以$开头,和AngularJS内置变量区分开来。
- Firefox安装插件AngScope;
Note03--MVC && scope
最新推荐文章于 2021-03-09 15:24:07 发布