最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Binding OBJECT ARRAY to OPTIONS VALUES of a SELECT in AngularJs - Stack Overflow

programmeradmin4浏览0评论

I have a hash of objects, and the ID of this hash is binding to a RADIO BUTTON. When the user select this radio, I need to populate a select tag with options based on attribute of this model. Its hard to explain, so I created a Codepen to show what I want:

Thanks in advance!

I have a hash of objects, and the ID of this hash is binding to a RADIO BUTTON. When the user select this radio, I need to populate a select tag with options based on attribute of this model. Its hard to explain, so I created a Codepen to show what I want: http://codepen.io/rizidoro/pen/BeJjf

Thanks in advance!

Share Improve this question asked Feb 28, 2013 at 18:32 rizidororizidoro 13.4k18 gold badges60 silver badges86 bronze badges 1
  • 1 why are you yelling at me :'( – jbabey Commented Feb 28, 2013 at 18:39
Add a ment  | 

3 Answers 3

Reset to default 3

Here's a codepen demo binding dynamically to a single SELECT element, with a working ng-model binding on selection change:

HTML:

<div ng-controller="TestCtrl">
  <ul>
    <li ng-repeat="attr in data">
      <input type="radio" name='data-attr' value='{{attr.id}}' ng-model="selected.id" />{{attr.name}}
    </li>
  </ul>

  <select ng-model="selected.value" ng-options="item.name for item in selectedAttr.values "></select>
</div>

JS:

function TestCtrl($scope) {
  $scope.selected = {};

  $scope.data =  [
    {"id":"113000",
      "name":"Size",
      "values":
          [{"id":"92029","name":"Size A"},
           {"id":"92030","name":"Size B"}]
    },
    {"id":"113002",
      "name":"Color",
      "values":
          [{"id":"94029","name":"Blue"},
           {"id":"94030","name":"Black"}]
    }
  ];

  $scope.$watch('selected.id', function(id){
    delete $scope.selected.value;
    angular.forEach($scope.data, function(attr){
      if(attr.id === id){
        $scope.selectedAttr = attr;
      }
    });
  });
}

I have created a fiddle, that may solve ur problem. http://jsfiddle/qY2Zz/.

  1. Seperated the data to a service.

    animateAppModule.service('data', function(){...})

  2. Assigned a model to the select box.

    ng-model="$scope.selectedOption"

http://jsfiddle/wagedomain/afuz5/

I rewrote your HTML a little - not using ul / li tags where a div or span would suffice. Makes it easier.

Basically, inside the ng-repeat, you can do this:

<div ng-repeat="attr in data">
      <input type='radio' name='data-attr' value='{{attr.id}}' />{{attr.name}}   
      <select ng-model="selected" ng-options="item.name for item in attr.values "></select>
</div>

It's the ng-options that makes this work. I also added a $scope.selected variable to model bind to but I'm not doing anything with it in the fiddle. Use as you need.

发布评论

评论列表(0)

  1. 暂无评论