控制AngularJS在一个控制器多个视图 [英] Controlling multiple views in one controller in AngularJS
问题描述
继MVC模式,一个控制器应能在AngularJS处理多个视图。
Following the MVC pattern, one controller should be able to handle multiple views in AngularJS.
例如。我有显示了用于创建一个新用户的所有用户,并一一查看。我的 $ routeProvider
(节选)看起来是这样的:
E.g. I have one view for showing all users and one for creating a new user. My $routeProvider
(excerpt) looks like this:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/showusers', {
templateUrl: 'partials/showusers.html',
controller: 'userController'
}).
when('/createuser', {
templateUrl: 'partials/showusers.html',
controller: 'userController'
})
}]);
这两种观点分享几种方法,如检索所有的用户属性。这些共享的方法是通过工厂
访问。
的 UserController的
(节选)目前看起来是这样的,其中用户
是一个工厂:
The userController
(excerpt) currently looks like this where Users
is a factory:
angular.module('supportModule').
controller('userController', function($scope, Users) {
var init = function(){
$scope.users = Users.getAll();
$scope.attributes = Users.getAttributes();
}
init();
})
问题是:我不需要请求 Users.getAll();
当我在 CREATEUSER
视图。
当然,我可以很容易地通过使用 $位置
解析路线, $ routeProvider
或纯JS和然后conditonally调用方法 - 但我想没有在角:)结果更加优雅和有效的方式
在典型的MVC框架,像其中一个控制器有许多行动 - 为每个视图
Of course, I could easily parse the route by using $location
, the $routeProvider
or pure JS and then conditonally call methods - but I figure there is a more elegant and efficient way in Angular :)
Something like in typical MVC frameworks where one controller has many actions - one for each view.
所以我的问题:结果
如何根据控制多个视图控制器的看法典雅的调用方法?
推荐答案
您可以使用解析:
时设置 $ routeProvider
取决于匹配的路由上值传递给控制器。
You could use resolve:
when setup $routeProvider
to pass values to a controller depending on the matched route.
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/showusers', {
templateUrl: 'partials/showusers.html',
controller: 'userController',
resolve: {
ctrlOptions: function () {
return {
getAllUsers: true,
};
}
}
}).
when('/createuser', {
templateUrl: 'partials/showusers.html',
controller: 'userController',
resolve: {
ctrlOptions: function () {
return {
getAllUsers: false,
};
}
}
})
}]);
然后在控制器,你可以注入的指定项目的决心:
是这样的:
app.controller('userController', function ($scope, Users, ctrlOptions) {
var init = function () {
if (ctrlOptions.getAllUsers) {
$scope.users = Users.getAll();
}
$scope.attributes = Users.getAttributes();
};
init();
});
希望这有助于。
这篇关于控制AngularJS在一个控制器多个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!