简体   繁体   中英

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). 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 .

Tagging your element in an ng-if will prevent the directive from initializing before it's needed. ( scope.loadModal should be false by default)

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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