How to configure Angularjs controllers? anonymous functions vs $ scope.init () vs view ng-init

Suppose we have a controller: ProjectsNewCtrl

What's the difference between:

Controller setup without function init()

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 using the function init()

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:

Controller setup with:

<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
        })
      }

  }])
+4
source share
2 answers

There is no real reason why you would like to use ngInitthis way. In the second example, you call the function ( ngInit) to call the function ( $scope.init) instead of the first example, when you call only one function during initialization. The logic may be the same, but it adds unnecessary complexity.

, ngInit , :

ngInit - ngRepeat, . , ngInit .

+2

. 2 , , , init - , - . - , , .

0

Source: https://habr.com/ru/post/1546924/


All Articles