4

Assume we have a controller: ProjectsNewCtrl

What is the difference between:

Setting up the controller without an init() function

App.controller('ProjectsNewCtrl', ['$scope', '$location', 'API'
  function ($scope, $location, API) {
    API.Project.query().$promise
      .then(function (projects) {
        $scope.projects = projects
      })
  }])

AND

Setting up the controller with an init() function

App.controller('ProjectsNewCtrl', ['$scope', '$location', 'API'
  function ($scope, $location, API) {
    $scope.init = function(){
      API.Project.query().$promise
        .then(function (projects) {
          $scope.projects = projects
        })
      }
    $scope.init()

  }])

AND finally:

Setting up the controller via:

<div ng-controller="projectsNewCtrl" ng-init="init()">...</div>

App.controller('ProjectsNewCtrl', ['$scope', '$location', 'API'
  function ($scope, $location, API) {
    $scope.init = function(){
      API.Project.query().$promise
        .then(function (projects) {
          $scope.projects = projects
        })
      }

  }])

2 Answers 2

2

There is no real reason why you would want to use ngInit in this way. In your second example, you are calling a function(ngInit) to call a function($scope.init), instead of the first example where you only call one function on initialization. The logic maybe the same, but it adds unnecessary complexity.

As an aside, you should try no to use ngInit as little as possible, coming from the documentation:

The only appropriate use of ngInit is 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.

Sign up to request clarification or add additional context in comments.

Comments

0

Preference. Your last 2 examples are essentially the same, the logic that should be ran on initialization is within the init method - one is called from the view and the other the controller. IMO - it's all about readability, choose what you like.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.