我有一个简单的父/子控制器设置如下:
<body ng-controller="ParentCtrl">
<section my-directive></section>
<div ng-controller="Child1Ctrl">
<button ng-click="child1()">Click Child1</button>
</div>
<br>
<div ng-controller="Child2Ctrl">
<button ng-click="child2()">Click Child2</button>
</div>
</body>
当我从 Child 1 Ctrl 或 Child 2 Ctrl单击任一按钮时,我希望更新 my-directive 中的范围。
myDirective.js
app.directive('myDirective', function () {
var slider = {
initial : function() {
slider.clear();
$scope.slideHide = false;
$scope.slideShow = false;
},
clear: function() {
$scope.slideMessage = '';
$scope.slideError = false;
$scope.slideSuccess = false;
},
error: function(message) {
$scope.slideShow = true;
$scope.slideError = true;
$scope.slideMessage = message;
},
success: function(message) {
$scope.slideShow = true;
$scope.slideSuccess = true;
$scope.slideMessage = message;
}
}
return {
restrict: 'A',
replace: true,
transclude: true,
template: '<section class="slide">' +
'<div data-ng-class="{\'slide-show\' : slideShow, \'slide-error\' : slideError, \'slide-success\' : slideSuccess, \'slide-hide\' : slideHide}">' +
'<p>{{ slideMessage }}</p>' +
'</div>' +
'</section>'
}
}
);
并在我的子控制器中调用:
app.controller('Child1Ctrl', function($scope) {
$scope.child1 = function () {
$scope.$parent.slider.initialise();
}
});
app.controller('Child2Ctrl', function($scope) {
$scope.child2 = function () {
$scope.$parent.slider.success('Display some text');
}
});
用小提琴更新:
http://jsfiddle.net/6uub3jqx/1/
如果您单击第一组按钮,则会出现红/绿丝带。
如果您单击带有 child1/2 控制器的按钮,则没有任何操作。
解决方案:
见小提琴:http: //jsfiddle.net/6uub3jqx/2/
基本上孩子应该发送:
$scope.successChild1 = function(msg) {
$scope.$emit('successCh1', 'Some data');
};
父母应该收到:
$scope.$on('successCh1', function (event, data) {
$scope.$broadcast('success', data);
});
rootscope 会是更好的选择吗?