angular中控制器之间的传值该怎么实现
1个回答
展开全部
Angularjs控制器之间传值有以下几种方式:
$emit只能向parent controller传递event与data( $emit(name, args) )
$broadcast只能向child controller传递event与data( $broadcast(name, args) )
$on用于接收event与data( $on(name, listener) )
<div ng-controller="ParentCtrl"> <!--父级-->
<div ng-controller="SelfCtrl"> <!--自己-->
<a ng-click="click()">click me</a>
<div ng-controller="ChildCtrl"></div> <!--子级-->
</div>
<div ng-controller="BroCtrl"></div> <!--平级-->
</div>
var app = angular.module('myApp', []);
app.controller('SelfCtrl', function($scope) {
$scope.click = function () {
$scope.$broadcast('to-child', 'child');
$scope.$emit('to-parent', 'parent');
}
});
app.controller('ParentCtrl', function($scope) {
$scope.$on('to-parent', function(event,data) {
console.log('ParentCtrl', data); //父级能得到值
});
$scope.$on('to-child', function(event,data) {
console.log('ParentCtrl', data); //子级得不到值
});
});
app.controller('ChildCtrl', function($scope){
$scope.$on('to-child', function(event,data) {
console.log('ChildCtrl', data); //子级能得到值
});
$scope.$on('to-parent', function(event,data) {
console.log('ChildCtrl', data); //父级得不到值
});
});
app.controller('BroCtrl', function($scope){
$scope.$on('to-parent', function(event,data) {
console.log('BroCtrl', data); //平级得不到值
});
$scope.$on('to-child', function(event,data) {
console.log('BroCtrl', data); //平级得不到值
});
});
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询