在运行链接功能之前,如何确保控制器中的数据已加载到指令中?
使用伪代码,我可以:
<my-map id="map-canvas" class="map-canvas"></my-map>
为我的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); } } }]);
以上将无法正常工作,因为console.log($ scope.paths.length);将在服务返回任何数据之前被调用。
最简单的解决方案是使用ng-if,因为只有当ng-if被解析为true时才会渲染元素和伪指令
原文链接:https://www.f2er.com/angularjs/144854.html<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',PathService) { $scope.paths = []; $scope.servicePromise = PathService.getPaths() },link: function (scope,attrs) { scope.servicePromise.then(function (data) { scope.paths = data; console.log(scope.paths) }); } }