javascript - Can I init an Angular ngModel in html, and then use its value in controller? -
html:
<div ng-controller="mycontroller"> <form> <!-- 1 way --> <input ng-model="var1" value="1"></input> <!-- 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 " + $scope.var1); console.log("value of var2 " + $scope.var2); $scope.var1 = 3; $scope.var2 = 4; }]); result:
value of var1 undefined value of var2 undefined [setting values 3 , 4 displays fine in inputs] so, seems controller code running before input ng-model params being evaluated. makes sense given controller announced earlier input tags.
question:
is there way have controller logic read , respect initial value of var1 , var2?
you cannot mix angular's ng-model , regular html value attributes.
if want initialize model, in controller (or using ng-init not recommended). , remove value html.
$scope.var1 = 3; $scope.var2 = 4; also, ng-init evaluated after controller first read, if want display value ng-init need $watch it: not there first time controller executed.
Comments
Post a Comment