gpt4 book ai didi

angularjs - 路由 Controller 解决混淆

转载 作者:行者123 更新时间:2023-12-04 05:09:19 24 4
gpt4 key购买 nike

我有 2 个解决方案的问题,每个 Controller 一个解决方案。

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

任何的想法?

最佳答案

这里的问题是 app.controller()不返回 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;
}
}
});
});

关于angularjs - 路由 Controller 解决混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15080341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com