0

I have a requirement to list, edit and delete an entity. I have different views for each of this operations. I want to know if it is a good practice to use the same Angular just controller for these operations that works with each of the operation or should there be a separate controller for each?

Also if using same controller for these operations, is it possible to call different function when different views are loaded? So when user goes to the list view, a list method is called on page load and when he goes to the edit view, an edit method of the controller is called on edit view's load. I manage to achieve this by calling the methods using ngInit but apparently that is not recommended in v1.2 and should only be used with ngRepeat.

My question is similar to this one. Angular - Using one controller for many coherent views across multiple HTTP requests

However I also want to know if there is a way to call different initialisation methods of the same controller depending on the view the controller is used by.

Community
  • 1
  • 1
Junaid
  • 1,708
  • 16
  • 25

2 Answers2

0

A better approach could be to write a utility service which can be used across the controller. Use this service in your different controllers.

Your service will look something like this:

(function() {
'use strict';
// this function is strict...

angular
    .module('myapp.services', [])
    .service('Utility', function() {
        var Utility = {};

        Utility.edit = function(id, dataset) {
          //perform edit related task here 
        };

        Utility.delete = function(id, dataset) {
          //perform edit related task here 
        };
        return Utility;
    })
}());
Aditya Sethi
  • 10,486
  • 11
  • 26
  • 31
  • I have got services setup, my question is more around using the same controller for different CRUD operations. – Junaid Oct 24 '14 at 07:16
  • In that case, you will have to create an object of functions in your main controller which you can define at your index.html Still I would suggest you to go for services as it is easy to understand and the code become more flexible. Any business related logic should be separated from controller :) – Aditya Sethi Oct 24 '14 at 07:21
0

I have got my answer here: Using same controller for all CRUD operations (Rails-alike)

Apparently it is a good practice to use a different controller for each view, and it shouldn't work as a service. This is quite different for someone coming from MVC/WebAPI into angular.

Community
  • 1
  • 1
Junaid
  • 1,708
  • 16
  • 25