我想延迟控制器的初始化,直到从服务器收到必要的数据为止。
我找到了针对Angular1.0.1的解决方案:延迟AngularJS路由更改,直到加载模型以防止闪烁,但无法使其与Angular1.1.0一起使用
模板
<script type="text/ng-template" id="/editor-tpl.html"> Editor Template {{datasets}} </script> <div ng-view> </div>
JavaScript
function MyCtrl($scope) { $scope.datasets = "initial value"; } MyCtrl.resolve = { datasets : function($q, $http, $location) { var deferred = $q.defer(); //use setTimeout instead of $http.get to simulate waiting for reply from server setTimeout(function(){ console.log("whatever"); deferred.resolve("updated value"); }, 2000); return deferred.promise; } }; var myApp = angular.module('myApp', [], function($routeProvider) { $routeProvider.when('/', { templateUrl: '/editor-tpl.html', controller: MyCtrl, resolve: MyCtrl.resolve }); });
http://jsfiddle.net/dTJ9N/1/
由于$ http返回了promise,因此创建自己的deferred仅在http数据到达时返回promise会对性能产生影响。您应该能够:
MyCtrl.resolve = { datasets: function ($http) { return $http({method: 'GET', url: '/someUrl'}); } };
如果您需要对结果进行某种处理,请使用.then,您的诺言将被免费链接:
MyCtrl.resolve = { datasets: function ($http) { return $http({method: 'GET', url: '/someUrl'}) .then (function (data) { return frob (data); }); } };