2

I have a html like this

<select data-ng-model="selection">
    <option value="">Select Search</option>
    <option value=1>One</option>
    <option value=2>Two</option>
    <option value=3>Three</option>
</select>
<input type="text" placeholder="search One" data-ng-model="search.one" data-ng-if="selection==1"/>
<input type="text" placeholder="search Two" data-ng-model="search.two" data-ng-if="selection==2"/>
<input type="text" placeholder="search Three" data-ng-model="search.three" data-ng-if="selection==3"/>
Selected: {{selection}}
Search by: {{search}}

In the above code, If an option is selected, the text box associated with that option is visible. But, if some input entered in the text box, the variable search ('search by' field in above code) is not getting updated. but if I delete data-ng-if, then search variable is getting updated properly.

What should I do to get search variable updated with data-ng-if?

Thank you!

Mike Vranckx
  • 5,557
  • 3
  • 25
  • 28
Manoj G
  • 71
  • 5
  • 1
    possible for duplicate http://stackoverflow.com/questions/18342917/angularjs-ng-model-doesnt-work-inside-ng-if – gaurav bhavsar Sep 01 '15 at 07:10
  • 1
    @gauravbhavsar: It worked for me. Now I am unsure what to do. Should I delete this question? or can you post this as answer and I'll accept... – Manoj G Sep 01 '15 at 07:29
  • you can not delete questions which have answers given, if you do this your account is blocked to ask question. – gaurav bhavsar Sep 01 '15 at 07:30

4 Answers4

1

Here is the solution Angularjs ng-model doesn't work inside ng-if

You have to use $parent to refer parent scope.

data-ng-model="$parent.search.one"
data-ng-model="$parent.search.two"
data-ng-model="$parent.search.three"
Community
  • 1
  • 1
gaurav bhavsar
  • 2,033
  • 2
  • 22
  • 36
0

try data-ng-model="$parent.search.one"

atinder
  • 2,080
  • 13
  • 15
0

This is happening because directives like ng-if, ng-repeat, ng-switch, ng-view and ng-include all create new child scopes.

To prevent it from creating its property in child scope you should use :

data-ng-model="$parent.search.one"

for better explanation on this topic please visit : https://github.com/angular/angular.js/wiki/Understanding-Scopes

It will clear all your doubts.

Juned Lanja
  • 1,466
  • 10
  • 21
0

Perhaps there is something strange in your controller, but In this JSFiddle, selecting a new option and changing the value in the text field updates the value in {{search}} just fine. https://jsfiddle.net/xx3bsafk/

Based on this other thread, mine works because the ng-models in the ng-if fields are tied to the children of an object, not the object itself (If you were trying to edit the object itself, javascript would have automatically created a new instance of object instead of referencing the object itself - because if creates a new scope like everyone is saying.)

Angularjs ng-model doesn't work inside ng-if

Community
  • 1
  • 1
Aaron Hull
  • 422
  • 4
  • 16