延迟控制器初始化

延迟控制器初始化

本文介绍了Angular.js 延迟控制器初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想延迟控制器的初始化,直到必要的数据从服务器到达.

我为 Angular 1.0.1 找到了这个解决方案:延迟 AngularJS 路由更改直到模型加载以防止闪烁,但不能让它与 Angular 1.1.0 一起工作

模板

<div ng-view>

JavaScript

function MyCtrl($scope) {$scope.datasets = "初始值";}MyCtrl.resolve = {数据集:函数($q,$http,$location){var deferred = $q.defer();//使用setTimeout代替$http.get来模拟等待服务器回复设置超时(功能(){console.log("随便");deferred.resolve("更新值");}, 2000);返回 deferred.promise;}};var myApp = angular.module('myApp', [], function($routeProvider) {$routeProvider.when('/', {templateUrl: '/editor-tpl.html',控制器:MyCtrl,解决:MyCtrl.resolve});});

http://jsfiddle.net/dTJ9N/1/

解决方案

由于 $http 返回一个 promise,所以创建自己的 deferred 只是为了在 http 数据到达时返回 promise 会影响性能.你应该能够做到:

MyCtrl.resolve = {数据集:函数($http){返回 $http({method: 'GET', url: '/someUrl'});}};

如果您需要对结果进行一些处理,请使用 .then,您的承诺将被免费链接:

MyCtrl.resolve = {数据集:函数($http){返回 $http({method: 'GET', url: '/someUrl'}).then(功能(数据){返回 frob(数据);});}};

I would like to delay the initialization of a controller until the necessary data has arrived from the server.

I found this solution for Angular 1.0.1: Delaying AngularJS route change until model loaded to prevent flicker, but couldn't get it working with Angular 1.1.0

Template

<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/

解决方案

Since $http returns a promise, it's a performance hit to create your own deferred just to return the promise when the http data arrives. You should be able to do:

MyCtrl.resolve = {
    datasets: function ($http) {
        return $http({method: 'GET', url: '/someUrl'});
    }
};

If you need to do some processing of the result, use .then, and your promise is chained in for free:

MyCtrl.resolve = {
    datasets: function ($http) {
        return $http({method: 'GET', url: '/someUrl'})
               .then (function (data) {
                   return frob (data);
               });
    }
};

这篇关于Angular.js 延迟控制器初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 12:46