Search code examples
javascripthtmlangularjsangular-ngmodel

Can I init an Angular ngModel in html, and then use its value in controller?


html:

<div ng-controller="MyController">
<form>
<!-- one way to do it -->
<input ng-model="var1" value="1"></input> 
<!-- another way, not approved per angular documentation outside of ngRepeat -->
<input ng-model="var2" ng-init="var2=2"></input>
</form>
</div>

js:

angular.module('myApp', []);
angular.module('myApp')
    .controller('MyController', ['$scope', function ($scope) {
  console.log("value of var1 is " + $scope.var1);
  console.log("value of var2 is " + $scope.var2);
  $scope.var1 = 3;
  $scope.var2 = 4;
}]);

View this in jsbin

Result:

value of var1 is undefined
value of var2 is undefined
[setting values to 3 and 4 displays fine in inputs]

So, it seems that the controller code is running before the input ng-model params are being evaluated. Which makes sense given that the controller is announced earlier than the input tags.

Question:

is there any way to have the controller logic read and respect the initial value of var1 and var2?


Solution

  • You cannot mix Angular's ng-model and the regular HTML value attributes.

    If you want to initialize your model, do it in your controller (or using ng-init but it is not recommended). And remove that value from your HTML.

    $scope.var1 = 3;
    $scope.var2 = 4;
    

    Also, ng-init is evaluated after the controller is first read, so if you want to display the value from the ng-init you need to $watch for it: it will not be there the first time your controller is executed.