angular js 事件

来源:互联网 发布:java获取不到cookie 编辑:程序博客网 时间:2024/06/05 05:22

(1)angular js支持的事件

  • ng-click
  • ng-dbl-click
  • ng-mousedown
  • ng-mouseenter
  • ng-mouseleave
  • ng-mousemove
  • ng-keydown
  • ng-keyup
  • ng-keypress
  • ng-change
(2)实例

         点击按钮,实现“测试”的显示与隐藏

<!DOCTYPE html><html ng-app="testEvent"><head lang="en">    <meta charset="UTF-8">    <title></title></head><body ng-controller="myctrl"><span ng-hide="isHide">测试</span><button ng-click="toggle()">隐藏/显示</button><script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script><script>    var app = angular.module(            "testEvent",            []    );    app.controller("myctrl",function($scope){        $scope.isHide = false;        $scope.toggle = function(){            $scope.isHide = !$scope.isHide;        }    });</script></body></html>

(3)自定义事件传播

               1.前提

                  必须有controller嵌套,否则无法接收事件

<div ng-controller="ParentCtrl">   <div ng-controller="SelfCtrl">     <a class="btn" ng-click="click()">click me</a>     <div ng-controller="ChildCtrl"></div>   </div>   <div ng-controller="BroCtrl"></div></div>
               这里四个controller的层级关系如下:
               

             所有的事件都是从SelfCtrl发出


            2.$broadcast

                事件发送的方法:

$scope.$broadcast
               事件的接收方法:

$scope.$on
              broadcast是从发送者向他的子scope发送事件的一个方法,所以父scope不会收到
angular.module('TestApp', ['ng']).controller('ParentCtrl', function($scope) { $scope.$on('to-child', function(e, d) {   console.log('关我毛事'); });}).controller('SelfCtrl', function($scope) {  $scope.click = function () {    $scope.$broadcast('to-child', 'haha');  }}).controller('ChildCtrl', function($scope){  $scope.$on('to-child', function(e, d) {    console.log('I\' the child, I got it', d);  });}).controller('BroCtrl', function($scope){  $scope.$on('to-child', function(e, d) {    console.log('关我毛事');  });});

            3.$emit

                事件发送的方法:

$scope.$broadcast
               只有父scope能够收到

angular.module('TestApp', ['ng']).controller('ParentCtrl', function($scope) { $scope.$on('to-parent', function(e, d) {    console.log('we are the parent, I got it', d); });}).controller('SelfCtrl', function($scope) {  $scope.click = function () {    $scope.$emit('to-parent', 'hehe');  }}).controller('ChildCtrl', function($scope){  $scope.$on('to-parent', function(e, d) {   console.log('关我毛事');  });}).controller('BroCtrl', function($scope){  $scope.$on('to-parent', function(e, d) {    console.log('关我毛事');  });});

           4.说明
              不管是$broadcast还是$emit,兄弟controller永远都不会收到事件



0 0