简体   繁体   English

如何控制角度指令的初始化?

[英]How can I control initialization of an angular directive?

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). 由于此指令连接到某些Web服务,我不希望它初始化,除非用户单击按钮并显示表单(以防止不必要的Web服务调用)。 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: 这是一个例子:

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的模板包含一个标记。

Tagging your element in an ng-if will prevent the directive from initializing before it's needed. ng-if标记元素将阻止指令在需要之前初始化。 ( scope.loadModal should be false by default) (默认情况下, scope.loadModal应为false)

<my-directive ng-if='loadModal'></mydirective>

Note: Setting scope.loadModal = false after showing the directive once will unload the directive from your DOM. 注意:在显示指令一次后设置scope.loadModal = false将从DOM中卸载指令。 Setting it back to true would reload the directive resulting in another http request. 将其设置为true将重新加载指令,从而产生另一个http请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM