Search code examples
angularjsng-options

ng-options for select box binding to hash


I'm a little confused on how to do a binding with AngularJS. I'm putting a <select> element in with an ng-model="variable.type". I've also got a $scope.type variable with is a hash table. The key of that hashtable is the variable.type.

So basically I want the select box to list all of the values from $scope.type, and then do the binding so that the variable.type is linked to the key of the hashtable. I'm just not sure how to specify the ng-options to do that.

<tr ng-repeat="variable in variables">
    <td>
        <select ng-model="variable.type" ng-options="????">
        </select>
    </td>
</tr>

Solution

  • If I'm understanding your question, you're basically asking how to use an object as a data source for ng-options. If $scope.type looks like this:

    $scope.type = {
        "type1": { value: "value1" },
        "type2": { value: "value2" },
        "type3": { value: "value3" }
    };
    

    And $scope.variables looks like this:

    $scope.variables = [
        {
          id: 1,
          name: "item1",
          type: "type1"
        },
        {
          id: 2,
          name: "item2",
          type: "type2"
        },
        {
          id: 3,
          name: "item3",
          type: "type3"
        }
    ];
    

    Then you could bind it up like this:

    <tr ng-repeat="variable in variables">
      <td>
        <select ng-model="variable.type" ng-options="key as vartype.value for (key, vartype) in type"></select>
      </td>
    </tr>
    

    Demo