emc
emc

Reputation: 333

Why populating ng-model inside forms should be followed by $scope.$apply?

I have a form:

<form name="placeThis" id="placeThis" novalidate ng-submit="submitForm();">
    <input type="hidden" ng-model="placeThis.target"/>
</form>

And i want to add default value to placeThis.target from my controller, like this:

$scope.placeThis = { target: 0 }

But it isn't working if im not adding $scope.$apply or wrapping it inside $timeout (which will run $scope.$apply for me) .

I can save other $scope values from the controller without any problem, but values inside forms most be written inside $timeout or they get lost on submit. Why is this happening?

Upvotes: 0

Views: 1778

Answers (2)

sylwester
sylwester

Reputation: 16498

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"

  };


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="homeCtrl">
    <form name="placeThisForm" id="placeThis" novalidate ng-submit="submitForm();">
      <label>Target</label>
      <input type="text" ng-model="placeThis.target" />
      <label>Name</label>
      <input type="text" ng-model="placeThis.name" />
    </form>
  </div>
</div>

Upvotes: 2

Zaitcev Yurii
Zaitcev Yurii

Reputation: 19

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>

Upvotes: 1

Related Questions