zoukankan      html  css  js  c++  java
  • Ⅶ.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>

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


    作者:cnljli
    欢迎转载,但还请尊重劳动果实,保留此段声明并注明原文链接。
  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    ubuntu安装CUDA及cuDNN
    SpringCloud Alibaba微服务实战九
    互联网人必看的中台理论,阿里腾讯架构师用大白话讲出来了
    $("form > input">) 可以匹配表单下所有的子级input元素
    $("form input") 可以匹配表单下所有的input元素
    移动通信网络中的 GTP 协议
    构建数据库云管平台 实现数据价值最大化
    PostgreSQL的安装和启动方法大全
    组选择器
  • 原文地址:https://www.cnblogs.com/cnlj/p/3449221.html
Copyright © 2011-2022 走看看