Hamid Barani Hamid Barani - 5 months ago 22
AngularJS Question

Angular - Using one controller for many coherent views across multiple HTTP requests

I have a simple Angular JS scenario. I show a list of experts in one view, and that list contains actions to edit an expert, which would be done in another view. These views are coming from server and are not in one file. They don't load together.

<!-- experts.html -->
<div ng-controller='expertController'>
<!-- showing the list of experts here -->
</div>


And in another file on the server I have:

<!-- expert.html -->
<div ng-controller='expertController'>
<!-- a form to edit/add an expert -->
</div>


And my controller is:

app.controller('expertController', function ($scope) {
$scope.getExperts = function () {
_.get('/expert/getexperts/', null, function (data) {
$scope.$apply(function () {
$scope.experts = data;
});
});
};

$scope.editExpert = function (index) {
_.get('/expert/getexpert/', { id: $scope.experts[index].Id }, function (data) {
$scope.$apply(function () {
$scope.expert = data;
});
});
};
});


However, no data would be shown in the edit form. I inspected scopes using Batarang, but
expert
object won't be shown.

The problem seems to be that I use one controller for two (and optionally more than two) views. However, as I've read some other questions on SO, it seems that the best practice is to have one controller per HTML view.

However, I think it's more coherent and consistent to have one
expertController
to do all CRUD operations, alongside other actions related to
expert
. I think it's a little ugly to have
expertEditController
for edit form and
expertListController
for the list HTML.

What is the best practice here? How can I have a coherent and semantically named controller, and at the same time support many views. In any MVC framework that I've seen till now, it's something routine to support many views via one controller.

Answer

Of course you can use many views with the same controller. For example: for editing and adding new items.

But you have to remember that each time the view is loaded the controller is initialized and fresh, new $scope is injected.

In your case it would be better to just use two separate controllers (one for experts and one for expert) and use -- optionally -- some service to communicate between those and maybe provide some caching mechanism.

UPDATE In case you want to provide some common/shared functionality between controllers the best way to go is to create and then inject a separate service. It keeps the code DRY.