Ⅶ.AngularJS的点点滴滴-- 事件

事件(和js一样有冒泡和捕获)


<html>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script>



<div ng-controller="parent">parent:{{detail}}

<div ng-controller="test">

myself:{{detail}} 

<div ng-controller="child">child:{{detail}}</div>

<button ng-click="addparent()">addparent</button>

<button ng-click="addchild()">addchild</button>

</div>

</div>

<script>

var app = angular.module('app', [])

.controller('parent', ['$scope',function($scope) {

    $scope.detail =1;

    $scope.$on('add',function(){

      $scope.detail +=1;

    });



}]).controller('child', ['$scope',function($scope) {

    $scope.detail =1;

    $scope.$on('add',function(){

      $scope.detail +=1;

    });



}]).controller('test', ['$scope',function($scope) {

   $scope.detail =1;

   $scope.$on('add',function(){

      $scope.detail +=1;

   });

   $scope.addparent=function(){

    $scope.$emit('add');

   };   

   $scope.addchild=function(){

    $scope.$broadcast('add');

   };

}]);

angular.bootstrap(document, ['app']);

</script>

</html>

从上面的代码可以看出$on来订阅一个事件,$emit触发的事件会冒泡处理, $broadcast触发的事件会捕获, 系统还有很多自带的事件可以订阅,比如路由成功与否的$routeChangeError$routeChangeSuccess

ng-bind-html-unsafe(新版本中被移除,可以新建指令依赖ngSanitize)


<html>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular-sanitize.js"></script>

<div ng-controller="parent" ng-bind-html-unsafe="html"></div>

<script>

angular.module('app', ['ngSanitize']).config(['$compileProvider',

function($compileProvider) {

  $compileProvider.directive({

    ngBindHtmlUnsafe: function() {

      return function(scope, element, attr) {

        element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);

        scope.$watch(attr.ngBindHtmlUnsafe,

        function ngBindHtmlUnsafeWatchAction(value) {

          element.html(value || '');

        });

      }

    }

  });

}]).controller('parent', ['$scope',

function($scope) {

  $scope.html = "<span>aaa</span>";

}]);

angular.bootstrap(document, ['app']);

</script>

</html>

前面了解了指令的用法后,应该觉得很简单啦


你可能感兴趣的:(AngularJS)