Angular: running function in controller when all directives are loaded

前端 未结 1 999
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 01:54

I\'m trying to come up with some code which allows me to run a function in the controller but only once the whole dom is setup and ready (including the directives link funct

相关标签:
1条回答
  • 2021-01-16 02:36

    Using $timeout would be terrible. Don't do that. You can't define how long a server call is going to take.

    I would recommend using this pattern:

    • Have the controller use a service to load some data, and have the promise in the controller assign the return data to a scope variable.
    • Pass that scope variable into your directive.
    • Setup a watch in the directive link function, when it loads it will go from undefined to desired value. Done!

    // in your controller

    YourService.all().then(function(data) {
      $scope.data = data;
    });
    

    // in your view

    <some-directive your-data="data"></some-directive>
    

    // in your directive

    angular.module('blah.directives').directive('someDirective', function() {
        return {
          scope: {
            yourData: '='
          },
          link: function(scope, element, attrs) {
    
            var watcher = scope.$watch('yourData', function() {
              if(scope.yourData === undefined) return;
    
              // at this point your data will be loaded, do work
    
              // optionally kill watcher at this point if it's not going to update again
              watcher();
            });
          }
        }
      });
    
    0 讨论(0)
提交回复
热议问题