Rob*_*tin 26 angularjs angularjs-directive
在运行链接功能之前,如何确保控制器中的数据已加载到指令中?
使用伪代码,我可以:
<my-map id="map-canvas" class="map-canvas"></my-map>
Run Code Online (Sandbox Code Playgroud)
为我的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);
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
以上操作无效,因为console.log($ scope.paths.length); 将在服务返回任何数据之前调用.
我知道我可以通过链接功能调用该服务,但想知道是否有办法在触发链接功能之前"等待"服务调用.
mau*_*ycy 44
最简单的解决方案是使用,ng-if因为只有在将ng-if其解析为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
}
)
})
Run Code Online (Sandbox Code Playgroud)
或使用承诺
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)
});
}
}
Run Code Online (Sandbox Code Playgroud)