gpt4 book ai didi

javascript - 如何访问指令链接中的 Controller 功能?

转载 作者:可可西里 更新时间:2023-11-01 02:51:11 25 4
gpt4 key购买 nike

如何从指令链接访问指令 Controller 函数?传递给链接的波纹管 Controller 是空的,我想在其中加入 show() hide() 函数。

我当前的指令:

app.directive('showLoading', function() {
return {
restrict: 'A',
// require: 'ngModel',
scope: {
loading: '=showLoading'
},
controller: function($scope, $element) {
return {
show: function() {
alert("show");
},
hide: function() {
alert("hide");
}
};
},
link: function($scope, $element, $attrs, controller) {
$scope.$watch('loading', function(bool) {
if (bool) {
controller.show();//undefined
} else {
controller.hide();
}
});
}
};
});

最佳答案

在作用域上发布是可行的,但不是最佳实践,因为它“污染”了作用域。与自己的 Controller 通信的正确方法是 require 它 - 然后它将作为参数提供给 link 函数,连同其他必需的指令。

另一个问题是如何在 Controller 上公开函数 - 这是通过使用 this.someFn 完成的,而不是通过返回对象。

app.directive('showLoading', function() {
return {
restrict: 'A',
require: ['ngModel', 'showLoading'], // multiple "requires" for illustration
scope: {
loading: '=showLoading'
},
controller: function($scope, $element) {
this.show = function() {
alert("show");
};

this.hide = function() {
alert("hide");
};
},
link: function($scope, $element, $attrs, ctrls) {
var ngModel = ctrls[0], me = ctrls[1];

$scope.$watch('loading', function(bool) {
if (bool) {
me.show();
} else {
me.hide();
}
});
}
};
});

关于javascript - 如何访问指令链接中的 Controller 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29193261/

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