【发布时间】:2013-10-09 02:28:21
【问题描述】:
我正在测试应用程序中实现我的第一个 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 也遵循此规则是否正确,或者还有其他一些最佳实践?
【问题讨论】:
-
排序 $scope.$on('$routeChangeSuccess', function (scope, next, current) { var path = $location.path(); });
标签: javascript angularjs model-view-controller controller