2

我有 2 个解决方案的问题,每个控制器一个解决方案。

http://jsfiddle.net/pvivera/RhAHy/

var app = angular.module('testApp', [], function($routeProvider){
    $routeProvider.when('/', {
        template: 'Home {{model}}',
        controller: 'HomeCtrl',
        resolve: HomeCtrl.resolve
    })
    .when('/About', {
        template: 'About {{model}}',
        controller: 'AboutCtrl',
        resolve: AboutCtrl.resolve
    });
});

var HomeCtrl = app.controller('HomeCtrl', function($scope, HomeCtrlData){
    $scope.model = HomeCtrlData;
});

HomeCtrl.resolve = {
    HomeCtrlData: function($q, $timeout){
        var deferred = $q.defer();
        $timeout(function(){
            return deferred.resolve('AboutCtrlResolver');
        }, 2000);
        return deferred.promise;
    }
};

var AboutCtrl = app.controller('AboutCtrl', function($scope, AboutCtrlData){
    $scope.model = AboutCtrlData;
});

AboutCtrl.resolve = {
    AboutCtrlData: function($q, $timeout){
        var deferred = $q.defer();
        $timeout(function(){
            return deferred.resolve('AboutCtrlResolver');
        }, 2000);
        return deferred.promise;
    }
};

在 jsfiddler 脚本中,当 HomeCtrl 想要解析 HomeCtrlData 我收到此错误 Unknown provider: HomeCtrlDataProvider <- HomeCtrlData

如果我在 HomeCtrl 中将 HomeCtrlData 更改为 AboutCtrlData 一切正常,似乎分配的唯一解析是 AboutCtrl.resolve

任何的想法?

4

1 回答 1

3

这里的问题是它app.controller()不返回控制器,而是返回您的应用程序模块。所以你分配app.resolve了两次,这就是为什么它对其中一个不起作用。

我建议您像这样内联解析函数:

var app = angular.module('testApp', [], function($routeProvider){
    $routeProvider.when('/', {
        template: 'Home {{model}}',
        controller: 'HomeCtrl',
        resolve: {
            HomeCtrlData: function($q, $timeout) {
                var deferred = $q.defer();
                $timeout(function(){
                    return deferred.resolve('HomeCtrlData');
                }, 2000);
                return deferred.promise;
            }
        }
    })
    .when('/About', {
        template: 'About {{model}}',
        controller: 'AboutCtrl',
        resolve: {
            AboutCtrlData: function($q, $timeout) {
                var deferred = $q.defer();
                $timeout(function(){
                    return deferred.resolve('AboutCtrlData');
                }, 2000);
                return deferred.promise;
            }
        }
    });
});
于 2013-02-26T08:33:16.843 回答