1. 程式人生 > >Angular $broadcast和$emit和$ond實現父子通信

Angular $broadcast和$emit和$ond實現父子通信

ctrl -a mit tro ng- mod 名稱 fun rom

<!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實現父子通信