首页 > 代码库 > Angular $broadcast和$emit和$ond实现父子通信
Angular $broadcast和$emit和$ond实现父子通信
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<script src="http://www.mamicode.com/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 = http://www.mamicode.com/result;
});
$scope.toParent = function () {
//向父级元素通过事件传值 $emit 约定:toParentEvent
$scope.$emit(
‘toParentEvent‘,
‘msg to my parent‘
);
}
});
</script>
</body>
</html>
Angular $broadcast和$emit和$ond实现父子通信
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。