在AngularJS指令中运行链接功能之前,请等待控制器中的数据

时间:2014-12-15 14:13:14

标签: angularjs angularjs-directive

如何在运行链接功能之前确保控制器中的数据已加载到指令中?

使用伪代码,我可以:

<my-map id="map-canvas" class="map-canvas"></my-map>

我的HTML。

在我的指令中,我可能会有这样的事情:

app.directive('myMap', [function() {



return{
    restrict: 'AE',
    template: '<div></div>',
    replace: true,
    controller: function ($scope, PathService) {

        $scope.paths = [];

        PathService.getPaths().then(function(data){
            $scope.paths = data;

        });

    },
    link: function(scope, element, attrs){
        console.log($scope.paths.length);

    }

}


}]);

以上不会起作用,因为console.log($ scope.paths.length);将在服务返回任何数据之前调用。

我知道我可以通过链接功能调用该服务,但想知道是否有办法等待&#34;等待&#34;在触发链接功能之前进行服务调用。

2 个答案:

答案 0 :(得分:43)

最简单的解决方案是使用ng-if,因为仅当ng-if被解析为真时才会呈现元素和指令

<my-map id="map-canvas" class="map-canvas" ng-if="dataHasLoaded"></my-map>

app.controller('MyCtrl', function($scope, service){
  $scope.dataHasLoaded = false;

  service.loadData().then(
    function (data) {
      //doSomethingAmazing
      $scope.dataHasLoaded = true
    }
  )
})

或使用承诺

return {
  restrict: 'AE',
  template: '<div></div>',
  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)
    });
  }
}

答案 1 :(得分:0)

app.directive('MyDirective', function() {
    return {
        controller: function() {
            this.$postLink = function() {
                // here will run after the link function and also after the binding came in
            };
        },
        controllerAs: 'vm'
    };
});

检查角度1.5 Components have a well-defined lifecycle,它适用于

的指令