angularJS随笔

时间:2022-05-24 09:22:19

1.作用域

基于作用域的事件传播

作用域可以像DOM节点一样,进行事件的传播。主要是有两个方法:

  • broadcasted :从父级作用域广播至子级 scope
  • emitted :从子级作用域往上发射到父级作用域
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.2.25/angular.min.js"></script>
</head>
<body>
<div ng-controller="EventController">
Root作用域<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作用域<tt>MyEvent</tt> count: {{count}}
<ul>
<li ng-repeat="item in [1, 2]" ng-controller="EventController">
Leaf作用域<tt>MyEvent</tt> count: {{count}}
</li>
</ul>
</li>
</ul>
</div>
<script type="text/javascript">
function EventController($scope) {
$scope.count = 0;
$scope.$on('MyEvent', function() {
$scope.count++;
});
}
</script>
</body>
</html>