javascript 如何控制角度指令的初始化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21859676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I control initialization of an angular directive?
提问by cava23
I have a directive that is used as a form control. This directive is hidden in a modal dialog and is shown when the user clicks a button to show the form. Since this directive connects to some web services, I don't want it to initialize unless the user clicks the button and the form displays (to prevent unnecessary web service calls). So, what I'm looking for is a good way for the parent controller to trigger the directive to execute some init code. Here is an example:
我有一个用作表单控件的指令。该指令隐藏在模态对话框中,并在用户单击按钮以显示表单时显示。由于此指令连接到某些 Web 服务,除非用户单击按钮并显示表单(以防止不必要的 Web 服务调用),否则我不希望它初始化。所以,我正在寻找的是父控制器触发指令以执行一些初始化代码的好方法。下面是一个例子:
App.controller('parentCtrl', ['$scope', function($scope) {
$scope.onButtonClick = function onButtonClick() {
// tell directive to init somehow
};
}]);
App.directive('myDirective', function() {
return {
restrict: 'E',
scope: {},
controller: function($scope, myService) {
function init() {
myService.getData().then(function(value) { //do init stuff });
}
}
});
Assume the template for parentCtrl contains a tag .
假设 parentCtrl 的模板包含一个 tag 。
回答by Gabe
Tagging your element in an ng-if
will prevent the directive from initializing before it's needed. (scope.loadModal
should be false by default)
在 中标记元素ng-if
将阻止指令在需要之前初始化。(scope.loadModal
默认情况下应该是假的)
<my-directive ng-if='loadModal'></mydirective>
Note: Setting scope.loadModal = false
after showing the directive once will unloadthe directive from your DOM. Setting it back to true would reload the directive resulting in another http request.
注意:scope.loadModal = false
显示指令一次后设置将从您的 DOM 中卸载指令。将其设置回 true 将重新加载指令,从而产生另一个 http 请求。