toddmotto / ama

Ask me anything!
20 stars 3 forks source link

Initialize the server data from ng-init directive via calling angular controller function? #47

Open ajayojha opened 8 years ago

ajayojha commented 8 years ago

We have developed one Enterprise application, The complete client side framework is built on AngularJS and the server side framework is on ASP.NET Web API. In the application we have 350+ html pages and 250+ Web APIs. There are lots of areas where we initialize the server data from ng-init directive via calling controller function. Because in our application all data is coming from the ASP.NET Web APIs. But I was surprised upon the documentation for ng-init, which says, in a nice bold outline :

The only appropriate use of ngInit for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

Also have concern on Angular-styleguide Documentation, which says :

Define a controller for a view, and try not to reuse the controller for other views. Instead, move reusable logic to factories and keep the controller simple and focused on its view. Why?: Reusing controllers with several views is brittle and good end-to-end (e2e) test coverage is required to ensure stability across large applications.

I would like to get feedback from you on my concerns.

Let me brief first what we are doing in the application, for showing a industries list we load the industry HTML page and show the server data. The HTML template code is shown below: <div ng-init="initIndustries()">....</div>

The "initIndustries" function will be called from initialized industryCtrl. industryCtrl.js code is shown below :

app.controller("industryCtrl",["$scope",function($scope){

//Sets the server data in the $scope property. $scope.initIndustries = function(){ //perform ajax request and set the data into the $scope property. }

$scope.initAddIndustry = function(){ // perform ajax request for getting a dropdown data on Add Industry Page. } }])

I have few concerns based on Angularjs Doc and Anglarjs-styleguide guideline on Keep Controller Focused which is mentioned below :

  1. Are we doing something wrong to initialize the data via function because all data is coming from the Server APIs?
  2. Current initialization approach is against the industry practices in AngularJS based application. if yes, then which approach we need to follow in the application?
  3. Do we need to create sperate controller for every view just for the shake of client side test coverage, as per the angularjs-styleguide?

The reason to implement the above approach(initialize the data from ng-init directive via controller function), Due to large application my initial thought was to follow MVC philosophy of decoupling the code and separation of concerns.