$on , $emit , $broadcast , $apply
Posted 董七
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了$on , $emit , $broadcast , $apply相关的知识,希望对你有一定的参考价值。
$scope.$on(‘事件名称‘,function(event,data){
//监听事件
});
$scope.$emit(‘事件名称‘,‘传递的数据‘);//子元素向父元素发送事件请求,传递数据;
$scope.$broadcast(‘事件名称‘,‘传递的数据‘);//父元素向子元素发送事件请求,传递数据;
$scope.$apply();//当数据值发送改变时,及时更新数据;
例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body ng-app="firstApp"> <div ng-controller="MyController"> <h1>This is the parent scope:{{answer}}</h1> <div ng-controller="MyController"> <h2>This scope inherits from the parent scope</h2> This prints ‘42‘:{{answer}} </div> </div> <div ng-controller="allEvent"> 接收子元素传递给父元素的值:{{all}} <div ng-controller="parentEvent"> <span ng-click="parentClick()">父级点击,向子级传数据</span> <div ng-controller="childEvent"> 它是parentEvent的子级 {{answer}} </div> </div> <div ng-click="clickAll">点击向allEvent发送数据</div> </div> </body> <script src="common/angular.js"></script> <script> var app=angular.module(‘firstApp‘,[]); app.controller(‘MyController‘,function($scope){ $scope.answer = 42; }).controller(‘parentEvent‘,function($scope){ $scope.parentClick = function (){ $scope.$broadcast(‘sendChild‘,12); $scope.$emit(‘sendAll‘,‘你好呀,我是子元素‘); } }).controller(‘childEvent‘,function($scope){ $scope.$on(‘sendChild‘,function (event , data){ console.log(‘child‘); console.log(event); console.log(data); $scope.answer = data; }) }).controller(‘allEvent‘,function($scope){ $scope.$on(‘sendAll‘,function (event , data){ console.log(‘child‘); console.log(event); console.log(data); $scope.all = data; }) }) </script> </html>
以上是关于$on , $emit , $broadcast , $apply的主要内容,如果未能解决你的问题,请参考以下文章
Angularjs中的事件广播-浅谈$broadcast,$emit,$on
Angularjs中的事件广播 —全面解析$broadcast,$emit,$on
$on , $emit , $broadcast , $apply