在AngularJS指令中运行链接功能之前,请等待控制器中的数据 [英] Wait for data in controller before link function is run in AngularJS directive

查看:64
本文介绍了在AngularJS指令中运行链接功能之前,请等待控制器中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

使用伪代码,我可以:

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

用于我的html.

在我的指令中,我可能会有类似的内容:

In my directive I might have something like this:

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);服务返回任何数据之前将被调用.

The above won't work because console.log($scope.paths.length); will get called before the service has returned any data.

我知道我可以从链接功能调用服务,但是想知道是否有一种方法可以在触发链接功能之前等待"服务调用.

I know I can call the service from the link function but would like to know if there is a way to "wait" for the service call before firing the link function.

推荐答案

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

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

<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)
    });
  }
}

这篇关于在AngularJS指令中运行链接功能之前,请等待控制器中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆