Ng-init via function

2019-02-06 13:59发布

问题:

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

回答1:

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();

}]);


回答2:

So there's really no need to use ng-init at all

Sometimes you would want to initialize something by passing data in the view, which might have its uses in a templated page such as .NET MVC, where you want to pass information from .NET to angular (controller already has the data and the easiest way is to pass this in a ViewBag).

To do this the "correct" way is roundabout, and hard to maintain since you have to embed a script tag with a fixed ID on the page and use javascript/jquery to pull the data into your scope in your controller, again using the hard-coded ID.

Either way breaks (well, kludges) the MVW-pattern of angular, so, I guess, pick your poison.