Ng-init via function

Asqan picture Asqan · Dec 16, 2013 · Viewed 66.7k times · Source

As you know, it is possible to initialize objects as follows:

<div ng-init="friends = [{name:'John', phone:'555-1276'},
                         {name:'Mary', phone:'800-BIG-MARY'},
                         {name:'Mike', phone:'555-4321'},
                         {name:'Adam', phone:'555-5678'},
                         {name:'Julie', phone:'555-8765'},
                         {name:'Juliette', phone:'555-5678'}]"></div>

Is it possible to define object similar like this but via a function:

<div ng-init="init()">

My aim is actually taking the objects from an API and show them in a list via ng-repeat

Answer

Sunil D. picture Sunil D. · Dec 16, 2013

The documentation says ng-init will take any expression. So yes, you can do what you want above as long as the associated scope defines a function called init() (and I also verified it for fun).

Note that the documentation says that ng-init is really only intended to be used for aliasing properties inside of an ng-repeat:

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.

Finally, note that you can simply initialize your variables when the controller is created. So there's really no need to use ng-init at all. For example:

var myApp = angular.module('myApp', []);

myApp.controller('myController', ['$scope', function($scope){

  $scope.init = function() {
    $scope.a = 'Apples';
    $scope.b = 'Bees';
    $scope.c = 'Zebras';
  };
  // runs once per controller instantiation
  $scope.init();

}]);