Wait for data in controller before link function is run in AngularJS directive

前端 未结 2 703
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 17:17

How can I ensure that data from a controller has been loaded in a directive before the link function is run?

Using psuedo-code, I could have:



        
2条回答
  •  耶瑟儿~
    2021-01-31 17:44

    The easiest solution would be to use ng-if since the element and directive would be rendered only when the ng-if is resolved as true

    
    
    app.controller('MyCtrl', function($scope, service){
      $scope.dataHasLoaded = false;
    
      service.loadData().then(
        function (data) {
          //doSomethingAmazing
          $scope.dataHasLoaded = true
        }
      )
    })
    

    or use promises

    return {
      restrict: 'AE',
      template: '
    ', replace: true, controller: function ($scope, PathService) { $scope.paths = []; $scope.servicePromise = PathService.getPaths() }, link: function (scope, element, attrs) { scope.servicePromise.then(function (data) { scope.paths = data; console.log(scope.paths) }); } }

提交回复
热议问题