Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding stops working in input within ng-if

Tags:

angularjs

For some reason binding doesn't work on an input within ng-if block in a directive

so this, doesn't work:

app.directive 'foo', ->
    restrict: 'E'
    scope:
       type:'='
    template: "<input ng-if=\"type === 'string'\" ng-model='filterText'>
                  <div> {{filterText}} </div>"


<foo type="'string'" />

it works fine outside of directive or without ng-if. Wrapping input inside of a div with ng-if not helping. Is it a bug?

jsbin link

like image 280
iLemming Avatar asked Sep 29 '14 19:09

iLemming


People also ask

Why binding is not working in Angular?

You have main issue is that you have used ngModel for select element. So when you select item from select element at that time value is changed in selectedIds[rowIndex] item. I have applied minor code refactoring in first div as per below it will helpful to you.

What does [( ngModel )] do?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.

What is* in ngIf?

The *ngIf directive is most commonly used to conditionally show an inline template, as seen in the following example. The default else template is blank.

What is difference between ng model and Ng bind?

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable. Save this answer.


2 Answers

It is caused by the ng-if introducing a new scope combined with the fact that you ng-model "has not dot in it".

This works:

template: "<div ng-init='holder={}'> <input ng-if=\"type === 'string'\" ng-model='holder.filterText'></div>
               <div> {{holder.filterText}}</div>"

See the directive info at https://docs.angularjs.org/api/ng/directive/ngIf and notice the text "This directive creates new scope." For the "dot-in-model", see for example Does my ng-model really need to have a dot to avoid child $scope problems? or https://egghead.io/lessons/angularjs-the-dot Basically when reading the value it will be read correctly traversing scope prototypes, but when modifying the value it will be written to the very own scope.

like image 149
Stephen Friedrich Avatar answered Sep 23 '22 20:09

Stephen Friedrich


Since ng-if creates a new scope, you just need to do this

ng-model='$parent.filterText'

Also, please check this answer.

like image 20
zs2020 Avatar answered Sep 20 '22 20:09

zs2020