我有一個簡單的父/子控制器設置更新指令範圍如下: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 - 您上面評論的好處是什麼? –