javascript - angularjs: input with ng-model tag does not appear in model until I type in it -
why properties not appear in model until user types in field?
i have simple form:
<form ng-controller="ctrlapplicantinfo vm"> <input id="name" name="name" ng-model="vm.applicantinfo.name" class="form-control" type="text" placeholder="name" /> <input id="age" name="age" ng-model="vm.applicantinfo.age" class="form-control" type="text" placeholder="age" /> </form>
and controller:
myapp.controller('ctrlapplicantinfo', ['$scope', '$http', '$interval', '$filter', function ($scope, $http, $interval, $filter) { var vm = this; $scope.$watch("vm.applicantinfo", function (newvalue, oldvalue) { console.log("something has changed"); console.log("newvalue: " + json.stringify(newvalue)); console.log("oldvalue: " + json.stringify(oldvalue)); }, true); }]);
what appears in console unexpected:
something has changed newvalue: undefined oldvalue: undefined has changed newvalue: {"name":"bob"} oldvalue: undefined has changed newvalue: {"name":"bob","age":"22"} oldvalue: {"name":"bob"}
what want/expect model instantiated empty strings "" or null.
newvalue: {"name":"bob","age":""} oldvalue: {"name":"", "age":""}
(edit) clarification: trying avoid initializing model in controller because it's redundant code - want fact have ng-model on input automatically show in model.
the first call $watch difficult understand. here happens:
- angular initiates scope view (set object , name, age undefined), cause view creates reference object, scope don't.
- angular detects change name property set bob
- angular detects change age property set age
Comments
Post a Comment