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

时间:2021-01-19 17:27:44

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

1 个解决方案

#1


12  

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中标记元素将阻止该指令在需要之前进行初始化。(范围。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. Setting it back to true would reload the directive resulting in another http request.

注意:设置范围。在显示指令后,loadModal = false,将从DOM卸载指令。将它设置为true将重新加载指令,导致另一个http请求。

#1


12  

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中标记元素将阻止该指令在需要之前进行初始化。(范围。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. Setting it back to true would reload the directive resulting in another http request.

注意:设置范围。在显示指令后,loadModal = false,将从DOM卸载指令。将它设置为true将重新加载指令,导致另一个http请求。