AngularJS:如何从子控制器更新指令作用域
AngularJS : How to update directive scope from child controllers
我有一个简单的父/子控制器设置如下:
<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>
当我点击任何一个按钮时,从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: '<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会是一个更好的选择吗?
看情况。你既可以使用Angular的事件,也可以使用(在我看来更好的方法)保留状态的服务,例如:
.factory('myOwnScope', function () {
return {};
});
// include myOwnScope as dependency and share the information
// between controllers and directive by its properties
// (any Angular service is just a singleton)
有几种方法可以做到这一点。哪一种方法是最好的取决于你想要达到的目标。
一种可能是向你的指令中注入数据。那么你就不需要$parent变量了。
它会像这样(但不能保证它能工作,因为你没有一个活塞或类似的东西)
在你的html中:
<section my-directive mytext="myobject.mymessage"></section>
在你的控制器中:
$scope.myobject = { mymessage: 'hi there' };
在你的指令中:
return {
restrict: 'A',
scope: { mytext: '=' }
template: '{{mytext}}'
}
相关文章:
- 如何从另一个控制器更新控制器的ng重复模型
- 可以从控制器更新工厂,但不能从指令更新
- ASP.NET Web API 控制器更新行
- 从另一个 Angular 控制器更新 ng-repeat
- 从控制器更新值时出现 ng-if 问题
- 离子和角度 - 从控制器更新/刷新视图
- AngularJS:从另一个控制器或JS调用控制器更新功能
- 使用滑块控制器更新地图数据/阴影?包括示例
- angularJS$watch在使用控制器更新数据时不在指令中工作
- ng模型没有从控制器更新到视图
- AngularJS从其他控制器更新$scope
- 从任何观察到的控制器更新模板
- 从父控制器更新服务值
- Ember.js从应用控制器更新模型
- AngularJS:如何从子控制器更新指令作用域
- 如何在Ember.js中使用不同的控制器更新hasMany
- 从多个控制器更新页面部分的最佳方式
- 在AngularJS中跨控制器更新$scope变量
- 在 CodeIgniter 中使用 AJAX 从控制器更新 DIV 框
- 从另一个控制器更新ng-repeat上的复杂滤波器