我有一个简单的父/子控制器设置更新指令范围如下:AngularJS:如何从子控制器
<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>
当我点击任一按钮,从儿童 Ctrl键或儿童 Ctrl,我希望我的指令中的范围得到更新。
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会是更好的选择吗?
@pixelbits - 感谢您的信息,您能提供一个例子吗? –
@pixelbits你是什么意思? “谈话很便宜,给我代码。” – Vidul
@ CPH4 - 您上面评论的好处是什么? –