Displaying sub-array in ng-repeat

試著忘記壹切 提交于 2019-12-05 10:16:23

I'm not sure I understand your question, but you can divide the models in optgroups and then have an option for each variant within each model:

<select>
        <option value="">Model</option>
        <optgroup ng-repeat="model in data" label="{{model.model}}">
          <option ng-repeat="variant in model.variants" value="{{model}}">{{ model.model + '-' + variant.color }}</option>
        </optgroup>
</select>

Please see this plunkr: http://plnkr.co/edit/rPNaGXEi0m9rvNkzQuBJ?p=preview

Alternatively, you have to flatten your array:

$scope.flatten = function(){
      var out = [];
      angular.forEach($scope.data, function(d){
        angular.forEach(d.variants, function(v){
          out.push({model: d.model, variant: v.color})
        })
      })
      return out;
    }

And then you can use ngSelect:

<select ng-model="myColor" ng-options="model.variant group by model.model for model in flatten()">
   <option value=""> -- select -- </option>
</select>

Here's the updated Plnkr: http://plnkr.co/edit/rPNaGXEi0m9rvNkzQuBJ?p=preview

This may not be the answer you're looking for, but AngularJS is always pushing you to work with view-models, meaning models tailored for the views.

Your example with the models & its nested variants is not a model which is tailored for the view you're trying to present, and so I would suggest creating a new model based on your current model.

This new model would have one entry per model per variant, and would be flat so that a single ng-repeat would easily iterate over them. You could even add a watch statement to "manufacturerModels", so that you can be sure the new model you create for the options ng-repeat is always up to date.

Another option, which would work with what you're trying to do would be to create a simple directive, which only copies its inner html without its tags, for example:

<noTags>someHtml</noTags> --> someHtml

I'll leave it to you to write this directive, as its fairly simple.

Then, to solve your problem you'd simply need to write a nested ng-repeat statement, something like this:

<select name="device[ [[$index]] ]" ng-model="selectedModel" ng-change="loadModelImage(selectedModel)">
    <option value="">Model</option>
    <noTags ng-repeat="model in manufacturerModels">
        <option ng-repeat="varient in model.varients" value="[[model.id]]">[[model.model]] [[varient.color]] [[varient.memory]]</option>
    </noTags>
</select>

The rendered html should simply provide a long list of option tags which have all the options you want.

You need to use the 'ngOptions' directive for that purpose. https://docs.angularjs.org/api/ng/directive/select The directive can take either an array of options or a hash (object) of options. And omit the 'ngRepeat' within 'option'.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!