Why Populating Ng-model Inside Forms Should Be Followed By $scope.$apply?
I have a form: And i w
Solution 1:
Please see demo below
You need to change name of your form from 'placeThis' to something else like 'placeThisForm'
otherwise you overwriting $scope.placeThis
values set in your controller.
Please see demo below
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope) {
$scope.placeThis = {
target: "One",
name: "Tim"
};
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app"><divng-controller="homeCtrl"><formname="placeThisForm"id="placeThis"novalidateng-submit="submitForm();"><label>Target</label><inputtype="text"ng-model="placeThis.target" /><label>Name</label><inputtype="text"ng-model="placeThis.name" /></form></div></div>
Solution 2:
I think your problem is in the form name. You can read more about angular form here https://docs.angularjs.org/api/ng/directive/form. It says:
If the name attribute is specified, the form controller is published onto the current scope under this name.
So, different object stored under this name in scope. Try to set different form name, like this:
<form name="placeThisForm"id="placeThis" novalidate ng-submit="submitForm();">
<input type="hidden" ng-model="placeThis.target"/>
</form>
And in your controller:
$scope.placeThis = { target: 0 }
Another way to set initial value is using ng-init
<form name="placeThisForm"id="placeThis" novalidate ng-submit="submitForm();">
<input ng-init="placeThis.target = 0"type="input" ng-model="placeThis.target"/>
</form>
Post a Comment for "Why Populating Ng-model Inside Forms Should Be Followed By $scope.$apply?"