AngularJS:如何从子控制器更新指令作用域
AngularJS:如何从子控制器更新指令作用域
我有一个简单的父/子控制器设置如下:
当我点击任何一个按钮时,无论是来自Child1Ctrl还是Child2Ctrl,我都希望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: '' } } );
并在我的子控制器中调用:
app.controller('Child1Ctrl', function($scope) { $scope.child1 = function () { $scope.$parent.slider.initialise(); } }); app.controller('Child2Ctrl', function($scope) { $scope.child2 = function () { $scope.$parent.slider.success('显示一些文本'); } });
使用fiddle更新:
http://jsfiddle.net/6uub3jqx/1/
如果你点击第一组按钮,红色/绿色的带子会出现。
如果你点击child1/2控制器中的按钮,没有任何动作。
解决方案:
参见fiddle:http://jsfiddle.net/6uub3jqx/2/
基本上,子级应该发送:
$scope.successChild1 = function(msg) { $scope.$emit('successCh1', '一些数据'); };
并且父级应该接收:
$scope.$on('successCh1', function (event, data) { $scope.$broadcast('success', data); });
是否使用rootScope会是一个更好的选择?
问题的出现原因是在AngularJS中,父指令与子控制器之间的通信问题。解决方法有两种:使用Angular事件或使用一个保留状态的服务。
在使用Angular事件的方法中,可以通过在父指令中使用`$broadcast`或`$emit`触发事件,然后在子控制器中使用`$on`监听事件来实现通信。
在使用服务的方法中,可以创建一个服务来保存状态,然后在父指令和子控制器中注入该服务,并通过该服务的属性来实现通信。
下面是一个使用服务的示例代码:
.factory('myOwnScope', function () { return {}; }); // 在父指令中注入myOwnScope服务 .directive('parentDirective', function (myOwnScope) { return { link: function (scope) { // 通过myOwnScope的属性来共享信息 myOwnScope.data = "Shared data"; } }; }); // 在子控制器中注入myOwnScope服务 .controller('childController', function ($scope, myOwnScope) { // 在子控制器中可以访问到父指令共享的数据 console.log(myOwnScope.data); });
更多关于这个问题的解决方法可以参考这里的答案:[http://stackoverflow.com/questions/17470419](http://stackoverflow.com/questions/17470419)。