angularjs - ng-model not working Angular js -


i trying update parent scope in nested ng-repeat loop doesn't work ! have literally been on 2 pass hours !

this nested loop:

<div ng-repeat="input in config" style="border: 1px solid #000;">     <div ng-repeat="inputproperty in input.inputstyle" style="border: 1px solid  #000;">         <input type="text" style="{{inputproperty.style}}" ng-model="loop.year">type in year</div> </div> 

filter:

<div ng-repeat="book in products | filter: loop.year">{{ book.bookname }}</div> 

fiddle:

http://jsfiddle.net/dcot7eof/

loop.year inside nested loop , loop.year in filter 2 different things.

in nested loop, when write ng-model="loop.year", angular looks scope hierarchy such variable , doesn't find it, creates it, on scope of nested loop.

in filter, trying read variable, angular looks scope hierarchy variable, doesn't find because variable created in nested loop downward in hierarchy, not upward. in other words, scope filter in parent of scope of nested loop.

as others have said, fix issue, add $scope.loop = { year: '' } in controller. add variable controller's scope. consequence, when angular looks scope hierarchy loop.year, resolve in both cases same variable.

you can avoid type of issues if use 'controller as' syntax, new in angular 1.2. syntax makes easier manage scope variables. here's view code looks using syntax:

<div ng-controller="myctrl ctrl">     <div ng-repeat="input in ctrl.config" style="border: 1px solid #000;">         <div ng-repeat="inputproperty in input.inputstyle">             <input ng-model="ctrl.loop.year">type in year</div>         </div>     </div> </div> <div ng-repeat="book in ctrl.products | filter: ctrl.loop.year">{{ book.bookname }}</div> 

note how ng-controller differs original code, , how variables prefixed ctrl. can choose name in place of ctrl. here's controller side:

function myctrl() {      this.products = [{         "bookname": "harryporter",             "year": "2000"     }, {         "bookname": "sleepless",             "year": "2003"     }];      this.config = [{         "title": "yearinput",             "width": "100",             "inputstyle": [{             "style": "background-color:green;"         }]     }];  }; 

$scope replaced this. however, this not same $scope. this here bound $scope.ctrl.

this way of doing things helps make view code more explicit , easier maintain, since can see controller controls variables.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -