Reputation: 24676
I'm implementing my first AngularJS controller in a test application and I'm having some difficulties.
I have a list of items that I'm getting from a RESTful web service and I'm trying to implement a basic CRUD logic for this items.
The list is shown in itemsList.htm
page and routing config is:
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' });
});
Then I have my 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) {
// ...
}
}
Now I want to add to the same controller a function that returns a certain item passing its ID and populate editItem.htm
page, but I don't know I to access this functon...
I mean: how can I map the path /items/:itemID
to this function?
Should I implement it in a different controller and change the route config?
NOTE I usually implement my web apps using Java and Spring MVC and I usually implement a single controller for each entity in my application (for example: ItemsController, CustomersController, etc.). Is it correct to follow this rule also with AngularJs or there is some other best-practice?
Upvotes: 1
Views: 287
Reputation: 42669
The way I would go about it would be to implement a ItemController
that handles only one item at a time. Again it depends upon how the html is structured.
In any case you need to retrieve the selected item id using the $routeParams collection.
In the controller you can do
if($routeParams.itemID) {
//you got the id. call the getItem
getItem(itemID).success(function(item) {
$scope.item=data;
});
}
This piece has to be added in either ItemsController if you use the same controller, or in case you create a new controller still same check would be required.
If you are using existing ItemsController the implementation should be like
if($routeParams.itemID) {
//same as above code
}
else {
getItems();
}
which means you dont want to load list in the scope for single item view.
Upvotes: 1