在 AngularJS 指令中运行链接函数之前等待控制器中的数据 [英] Wait for data in controller before link function is run in AngularJS directive
问题描述
如何确保在运行链接函数之前已将来自控制器的数据加载到指令中?
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-如果
被解析为真
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屋!