我有一个从我的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。
有没有办法可以优雅地使我的指令在数据可用时才开始对数据起作用?我可以想到几个解决方案,但我对任何人都不满意:
答案 0 :(得分:4)
保持formData
falsey(null
/ undefined
有效),直到数据加载并使用ng-if。该指令仅在ng-if为真时编译。
<form-component ng-if="myController.formData" form-data="myController.formData"></form-component>