从AngularJS中的父控制器调用指令的方法 [英] Calling directive's methods from parent controller in AngularJS
问题描述
我正在使用 AngularJS 与别名控制器模式。我无法从父控制器访问(或我不知道如何)指令方法。
I am using AngularJS with the alias controllers pattern. I can't access (or I don't know how to) directive methods from a parent controller.
我的控制器里面有一个函数,它应该调用一个指令方法,但是这个指令方法在这个
控制器值。
I have a function inside my controller that should call a directive method but this directive method is not available inside the this
controller value.
这是我所拥有的。我做错了什么?
This is what I have. What I am doing wrong?
JS
angular.module('myApp', []).
controller('MyCtrl', function(){
this.text = 'Controller text';
this.dirText = 'Directive text';
this.click = function(){
this.changeText();
}
})
.directive('myDir', function(){
return {
restrict: 'E',
scope: {
text: '='
},
link: function(scope, element, attrs){
scope.changeText = function(){
scope.text = 'New directive text';
};
},
template: '<h2>{{text}}</h2>'
};
});
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl as ctrl">
<h1>{{ctrl.text}}</h1>
<my-dir text="ctrl.dirText"></my-dir>
<button ng-click="ctrl.click()">Change Directive Text</button>
</div>
</div>
此处代码的代码。
推荐答案
如果您严格使用孤立的 / code>在一个指令内,那么指令方法只能通过使用角度事件(例如
$ broadcast
& $ emit
If you strictly want to use isolated scope
inside a directive then the directive method can be only called by using angular events such as $broadcast
& $emit
在您的情况下,您需要使用 $ broadcast
将事件发送到整个 $ rootScope
In your case, you need to use $broadcast
to send event to entire $rootScope
您的代码将成为这样。
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl as ctrl">
<h1>{{ctrl.text}}</h1>
<my-dir text="ctrl.dirText"></my-dir>
<button ng-click="ctrl.click()">Change Directive Text</button>
</div>
</div>
代码
angular.module('myApp', []).
controller('MyCtrl', function($rootScope){
var that = this;
this.text = 'Controller text';
this.dirText = 'Directive text';
this.click = function(){
$rootScope.$broadcast('changeText',{});
}
}).
directive('myDir', function(){
return {
restrict: 'E',
scope: {
text: '='
},
link: function(scope, element, attrs){
scope.changeText = function(){
scope.text = 'New directive text';
};
scope.$on('changeText',function(event, data){
scope.changeText()
});
},
template: '<h2>{{text}}</h2>'
};
});
而不是调用子范围的方法,您需要广播一个事件,而且必须收听通过指令范围&在收听该事件之后,它将触发 changeText
方法。
Instead of calling method of child scope, you need to broadcast an event and that will have to be listened by the directive scope & it will fire changeText
method after listening to that event.
注意
使用服务/工厂将是更好的方法。
Using service / factory would be better approach.
This would be hopefully help you. Thanks.
这篇关于从AngularJS中的父控制器调用指令的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!