我正在测试应用程序中实现我的第一个 AngularJS Controller ,但遇到了一些困难。
我有一个从 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) {
// ...
}
}
现在我想向同一个 Controller 添加一个函数,该函数返回某个项目并传递其 ID 并填充 editItem.htm
页面,但我不知道要访问该函数...
我的意思是:如何将路径 /items/:itemID
映射到此函数?
我应该在不同的 Controller 中实现它并更改路由配置吗?
注意 我通常使用 Java 和 Spring MVC 实现 Web 应用程序,并且通常为应用程序中的每个实体实现一个 Controller (例如:ItemsController、CustomersController 等)。在 AngularJs 中也遵循此规则是否正确,或者还有其他最佳实践吗?
最佳答案
我的方法是实现一个一次只处理一个项目的ItemController
。同样,这取决于 html 的结构。
无论如何,您都需要使用 $routeParams 集合检索所选项目 ID。
在 Controller 中你可以做
if($routeParams.itemID) {
//you got the id. call the getItem
getItem(itemID).success(function(item) {
$scope.item=data;
});
}
如果您使用相同的 Controller ,则必须将这一部分添加到 ItemsController 中,或者如果您创建新的 Controller ,则仍然需要进行相同的检查。
如果您使用现有的 ItemsController,则实现应该类似于
if($routeParams.itemID) {
//same as above code
}
else {
getItems();
}
这意味着您不想在单个项目 View 的范围内加载列表。
关于javascript - AngularJs:对 Controller 的实现存疑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19141430/