rizidoro rizidoro - 5 months ago 16
AngularJS Question

Binding OBJECT ARRAY to OPTIONS VALUES of a SELECT in AngularJs

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!

Answer

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;
      }
    });
  });
}