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

前端 未结 2 1524
日久生厌
日久生厌 2021-01-28 04:45

I have a form:

相关标签:
2条回答
  • 2021-01-28 04:53

    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>
    
    0 讨论(0)
  • 2021-01-28 05:04

    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>

    0 讨论(0)
提交回复
热议问题