调用指令在AngularJS从父控制器方法 [英] Calling directives 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>
这里一个codePEN与code。
Here a codepen with the code.
推荐答案
如果您希望只使用隔离范围
里面的指令,然后该指令的方法可以使用只叫棱角分明的事件,如 $广播
&安培; $发出
If you want to strictly use isolated scope
inside directive then the directive method can be only called by using angular events such as $broadcast
& $emit
在你的情况,你需要使用 $广播
发送事件整个 $ rootScope
In your case you need to use $broadcast
to send event to entire $rootScope
您code会变成这个样子。
You Code will become like this.
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
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 event and that will listen by the directive scope & it will file changeText
method after listening that event.
注意
使用服务/工厂将是更好的办法。
Using service / factory would be better approach.
这是希望能帮助你。谢谢你。
This would be hopefully help you. Thanks.
这篇关于调用指令在AngularJS从父控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!