我正在测试应用程序中实现我的第一个AngularJS控制器,我遇到了一些困难。
我有一个从RESTful Web服务获得的项目列表,我正在尝试为这些项目实现基本的CRUD逻辑。
该列表显示在itemsList.htm
页面中,路由配置是:
app.config(function ($routeProvider) {
$routeProvider
.when('/items',
{
controller: 'ItemsController',
templateUrl: 'app/Partials/itemsList.htm'
})
.when('/items/:itemID',
{
controller: 'ItemsController',
templateUrl: 'app/Partials/editItem.htm'
})
.otherwise({ redirectTo: '/items' });
});
然后我有ItemsController
:
app.controller('ItemsController', function ($scope, $routeParams, $location, itemsService) {
$scope.status;
$scope.items;
getItems();
function getItems() {
itemsService.getItems()
.success(function (items) {
$scope.items = items;
})
.error(function (error) {
$scope.status = 'Unable to load items: ' + error.message;
});
}
function getItem(ID) {
// ...
}
}
现在我想在同一个控制器中添加一个函数,该函数返回一个传递其ID并填充editItem.htm
页面的项目,但我不知道我要访问这个功能......
我的意思是:如何将路径/items/:itemID
映射到此功能?
我应该在不同的控制器中实现它并更改路由配置吗?
注意我通常使用Java和Spring MVC实现我的Web应用程序,我通常为应用程序中的每个实体实现一个控制器(例如:ItemsController,CustomersController等)。使用AngularJs遵循此规则是否正确,还是有其他一些最佳实践?
答案 0 :(得分:1)
我将采用的方式是实现一次只能处理一个项目的ItemController
。再次,它取决于html的结构。
在任何情况下,您都需要使用$ routeParams集合检索所选的项目ID。
在控制器中你可以做
if($routeParams.itemID) {
//you got the id. call the getItem
getItem(itemID).success(function(item) {
$scope.item=data;
});
}
如果您使用相同的控制器,则必须在ItemsController中添加此部分,或者如果您创建新控制器,则仍需要进行相同的检查。
如果您正在使用现有的ItemsController,那么实现应该像
if($routeParams.itemID) {
//same as above code
}
else {
getItems();
}
这意味着你不想在单项视图的范围内加载列表。