简体   繁体   中英

Initialize data with init() call or ng-init?

In my AngularJS app, I have to init some values onload.

I wrote a function init() in this mind.

function init() {
    this.var = 'example';
}

Is it better to call init function at the end of my JS script, or with the ng-init attribute?

Solution 1

/* script.js */
function init() { /* instructions */ }
init();

Solution 2

/* script.js */
function init(){ // instructions // }}
// Not calling init() here

<!-- file.html -->
<div ng-controller="exampleCtrl as example" ng-init="example.init()">

If this is going to initialise some values ready for a page using them, you'd be using a controller, correct? So use the built in method for this called $onInit() ...

$onInit() {
  $scope.foo = 'some value';
  // Initialise other variables;
}

The $onInit() was added in AngularJS 1.5 for component controllers, but it works with all controllers.

From the ngInit docs :

This directive can be abused to add unnecessary amounts of logic into your templates . There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope .

So when you have the choice, always prefer to initialize in your controller: Solution 1 is better.


More broadly, in terms of separation of concerns , I would advice to write the logic in your controller. If you have a common part of code used by several controllers, move it to a service. This will greatly simplify the maintainability of your application when growing up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM