简体   繁体   中英

nested ng-repeat on two separate arrays

More than finding a way to resolve this, I am now interested in understanding why this is not working.

Let's say I have this array in angular:

 $scope.movieThemes = [ 'Fiction', 'Drama'];

And another array with with movies like:

$scope.movies=[{theme:'Drama', movie:'One million dollar baby'}, {theme:'Drama', movie:'Green mille'},{theme:'Fiction', movie:'Avatar'}, {theme:'Fiction', movie:'The Hobbit'}]

I have an ngRepeat with my themes

<div ng-repeat= "t in movieThemes">

And a nested datalist filtering the themes:

ng-repeat="m in movies|filter:{theme:t}

Where t is from the parent repeater like:

 <datalist id="movieList">
    <option ng-repeat="m in movies|filter:{theme:t}" value="{{m.movie}} - {{t}}"></option>
  </datalist>

OK as you can confirm on my fiddle this is not working:

Online Demo

But the question is why not?

Worth to mentioned without a data list it works fine:

Without Data List Demo

Try like this. i change your filter function syntax and also add select tag to dataList .

Edit: Your problem cuase for datalist id. ie your datalist ids in ne-repeat are same. i change datalist ids by adding $index to it. now it work correctly.

 var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', ["$scope",function MyCtrl($scope) { $scope.movieThemes = [ 'Fiction', 'Drama']; $scope.movies=[ {theme:'Drama', movie:'One million dollar baby'}, {theme:'Drama', movie:'Green mille'}, {theme:'Fiction', movie:'Avatar'}, {theme:'Fiction', movie:'The Hobbit'} ]; }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="MyCtrl"> <div ng-repeat= "t in movieThemes"> <input type="text" ng-model="t" /> {{t}} - {{$index}} <input type="text" placeholder="Users" list="movieList{{$index}}"> <datalist id="movieList{{$index}}"> <select> <option ng-repeat="m in movies|filter:{theme:t}" value="{{m.movie}} - {{t}}"></option> </select> </datalist> </div> </div> 

You can use groupBy filter. This way you don't need wot worry about themes array. You can write your own/use angular filters module.( https://github.com/a8m/angular-filter )

<ul>
  <li ng-repeat="(key, value) in movies| groupBy: 'theme'">
    Group name: {{ key }}
    <ul>
      <li ng-repeat="m in value">
        player: {{ m.movie}}
      </li>
    </ul>
  </li>
</ul>

BTW I like angular filters modules

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM