Srinivasan A
Srinivasan A

Reputation: 51

Resolving ng-model outside the form

I have an html file with 2 form elements with input elements inside both. I would be using the ng-if to select which form element I need. The input elements are bound to the same model. But I am unable to resolve it outside the form scope.

<form ng-if="some_name == '1'">
 <input ng-model="model_name">
</form>

<form ng-if="some_name == '2'">
 <input ng-model="model_name">
</form>

{{model_name}} //This is different from the value of either of the input elements
//it has the initial value which i would assign : $model_name = "xyz"; in my associated js file

Upvotes: 0

Views: 1723

Answers (1)

Gaurav
Gaurav

Reputation: 1233

The reason you are not able to see those changes outside your form is because you are using 'ngIf' directive to add/remove the DOM and also the 'ngIf' directive creates a new scope.

There are two quick ways to solve this: 1) Make use of 'ngShow'. Look at the below example:

angular.module('app', [])
  .controller('HomeController', function($scope) {
    $scope.model_name = 'Hi';
    $scope.some_name = '1';
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div data-ng-app="app" data-ng-controller="HomeController">

  <form ng-show="some_name == '1'">
    <input ng-model="model_name">
  </form>

  <form ng-show="some_name == '2'">
    <input ng-model="model_name">
  </form>

  {{model_name}}

</div>

2) Make the input model an object, instead of a primitive.

angular.module('app', [])
  .controller('HomeController', function($scope) {
    $scope.model_name = {
      value: 'Hi'
    };
    $scope.some_name = '1';
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div data-ng-app="app" data-ng-controller="HomeController">

  <form ng-if="some_name == '1'">
    <input ng-model="model_name.value">
  </form>

  <form ng-if="some_name == '2'">
    <input ng-model="model_name.value">
  </form>

  {{model_name.value}}

</div>

Upvotes: 3

Related Questions