gpt4 book ai didi

javascript - 在 AngularJS 中从父 Controller 调用指令的方法

转载 作者:行者123 更新时间:2023-12-03 00:39:14 25 4
gpt4 key购买 nike

我正在将 AngularJS 与别名 Controller 模式一起使用。我无法从父 Controller 访问(或者我不知道如何)指令方法。

我的 Controller 内有一个函数应该调用指令方法,但此指令方法在 this Controller 值内不可用。

这就是我所拥有的。我做错了什么?

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>

Here带有代码的代码笔。

最佳答案

如果您严格希望在指令内使用独立的scope,则只能通过使用 Angular 事件来调用指令方法,例如$broadcast$emit

在您的情况下,您需要使用 $broadcast 将事件发送到整个 $rootScope

你的代码将会变成这样。

Working Code Pen

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 方法。

注意

Using service / factory would be better approach.

希望这对您有帮助。谢谢。

关于javascript - 在 AngularJS 中从父 Controller 调用指令的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28116680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com