码迷,mamicode.com
首页 > 其他好文 > 详细

Angular $broadcast和$emit和$ond实现父子通信

时间:2017-08-04 11:58:51      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:ctr   r.js   utf-8   传值   处理   body   angular   dct   result   

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<script src="js/angular.js"></script>
<title></title>
</head>
<body>

<div ng-controller="parentCtrl">
<button ng-click="toChild()">
向child传值
</button>

<div ng-controller="childCtrl">
<p>{{data}}</p>
<button ng-click="toParent()">向parent传值</button>
</div>

</div>


<script>
var app = angular.module(‘myApp‘, [‘ng‘]);

app.controller(‘parentCtrl‘, function ($scope) {
$scope.toChild = function () {
//通过事件传值 约定事件名称:toChildEvent
$scope.$broadcast(
‘toChildEvent‘,
‘ msg from parent‘)
}

//绑定toParentEvent事件的处理函数
$scope.$on(‘toParentEvent‘,
function (event, result) {
console.log(result);
})

});

app.controller(‘childCtrl‘, function ($scope) {
//绑定事件 $on
$scope.$on(‘toChildEvent‘,
function (event, result) {
console.log(arguments);
$scope.data = result;
});

$scope.toParent = function () {
//向父级元素通过事件传值 $emit 约定:toParentEvent
$scope.$emit(
‘toParentEvent‘,
‘msg to my parent‘
);
}

});

</script>
</body>
</html>

Angular $broadcast和$emit和$ond实现父子通信

标签:ctr   r.js   utf-8   传值   处理   body   angular   dct   result   

原文地址:http://www.cnblogs.com/dianzan/p/7284246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!