赞
踩
一 点睛
1 神奇的$scope
2 $scope的生命周期
3 事件机制
因为Scope的作用域范围不同,所以不同的Scope之间若有交互的话需要通过事件(Event)机制来完成
1 冒泡(Emit)冒泡事件负责从子Scope向上发送事件。
子Scope发送:
$scope.$emit('EVENT_NAME_EMIT','message');
父Scope接受:
$scope.$on('EVENT_NAME_EMIT',function(event,data)
{
......
})
2 广播事件(Broadcast)。广播负责从父Scope向下发送事件。
父Scope发送:
$scope.$broadcast('EVENT_NAME_BROAD','message');
子Scope接受:
$scope.$broadcast('EVENT_NAME_BROAD',function(event,data){
.....
})
二 实战
1 演示代码
- <!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>
2 编写控制器
- function EventController($scope) {
- $scope.count = 0;
- $scope.$on('MyEvent', function() {
- $scope.count++;
- });
- }
3 演示
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。