如何使Angular指令等待隔离范围数据可用?

时间:2015-04-09 19:54:11

标签: javascript angularjs angularjs-directive

我有一个从我的API加载数据的控制器。不幸的是,我有一个场景,我不能使用解决方案来加载数据。

angular.module('myApp').controller('myController', function() {
    var myController = this;

    formService.find('123').then(function(response) {
        myController.formData = response.data;
    });
});

我的控制器模板然后使用一个使用此数据的指令:

<form-component form-data="myController.formData"></form-component>

指令:

angular.module('myApp').directive('formComponent', function() {
    'use strict';

    return {
        restrict: 'E',
        scope: {
            formData: '=',
        },
        templateUrl: 'formComponent.html',
        link: function($scope, element, attrs) {
            // Outputs "undefined" as this is not yet loaded when
            // this directive runs.
            console.log($scope.formData);
        }
    };
});

正如您所看到的,当指令运行时,API尚未返回数据,因此访问时未定义$ scope.formData。

有没有办法可以优雅地使我的指令在数据可用时才开始对数据起作用?我可以想到几个解决方案,但我对任何人都不满意:

  1. 广播指示数据已加载的事件。
  2. 在指令中放置$ watch,然后在监视回调运行时取消绑定监视。

1 个答案:

答案 0 :(得分:4)

保持formData falsey(null / undefined有效),直到数据加载并使用ng-if。该指令仅在ng-if为真时编译。

<form-component ng-if="myController.formData" form-data="myController.formData"></form-component>