简体   繁体   中英

how to check if ng-init is processed without using $scope in angularjs?

Html code

<div ng-controller = "ctrl as ct">
 <input type="text" ng-model="ct.recentTurn" ng-init = "ct.recentTurn="555">
</div>

Angular Code

(function() {
  angular.module("app", []).controller("ctrl", mainCtrl);
  mainCtrl.$inject =["$scope"];
  function mainCtrl($scope){
     var ctrl = this;
     console.log(this.recentTurn); // this give undefined
     $scope.$watch("ct.recentTurn", function(old, newv){
       console.log(old);
       console.log(newv);
       //these two give correct value 555.
     });
}
})();

I want to call a function when controller is loaded with parameter recentTurn, but when controller is loaded recentTurn is not defined&initialized as i wanted. Value recentTurn will be thrown from server. Using $scope.$watch function would solve the issue, but i want to avoid using $scope. So is there anyway i could find when ng-init initialize the variable?

The reason your variable is undefined in the controller body is because a controller-function acts as a constructor. This constructor is called whenever the controller's scope is created, which in your case is when <div ng-controller="ctrl as ct"> is compiled and the controller's scope is bound to the DOM.

Since your ng-init is nested within the ng-controller directive, it will be bound (and thus evaluated) after the controller constructor function has been called. This means your line

console.log(this.recentTurn); // this give undefined 

is called before the expression in ng-init is evaluated.

Using ng-init for initializing simple variables may be considered bad practice, since you're basically placing application logic in your template/view. This is undesirable. There are actually very few usecases where ng-init is considered a valid, which you can read more about in the documentation (the big red warning box) . Instead of using ng-init you should simply initialize the variable in your controller.

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