16

I am new is angularjs and i am trying to get the index value in ng-repeat means i want to set md-option value as index value my code is:

<md-input-container class="md-block" flex-gt-sm>
    <label>Filterable Columns</label>
        <md-select ng-model="visualization.filterable_columns" ng-change="drawFilters()" multiple="true" ng-init="index = 1">
            <md-option ng-repeat="filterable_column in vm.filterable_columns" value="{{index++}}">
                {{filterable_column.label}
            </md-option>
        </md-select>
</md-input-container>

can anyone help me about this?

3
  • 1
    Warning: Using $index may not be advisable, q.v. here. Commented Dec 15, 2016 at 6:37
  • is there any another way..please !! Commented Dec 15, 2016 at 6:39
  • $index issue may not be, here Commented Aug 1, 2024 at 11:09

3 Answers 3

19

you can try like this:

<md-input-container class="md-block" flex-gt-sm>
    <label>Filterable Columns</label>
        <md-select ng-model="visualization.filterable_columns" ng-change="drawFilters()" multiple="true">
            <md-option ng-repeat="filterable_column in vm.filterable_columns" ng-value="{{$index}}">
                {{filterable_column.label}}
            </md-option>
        </md-select>
</md-input-container>
Sign up to request clarification or add additional context in comments.

Comments

11

Add track by $index to your ng-repeat

<md-input-container class="md-block" flex-gt-sm>
   <label>Filterable Columns</label>
   <md-select ng-model="visualization.filterable_columns" ng-change="drawFilters()" multiple="true">
      <md-option ng-repeat="filterable_column in vm.filterable_columns track by $index" ng-value="{{$index}}">
         {{filterable_column.label}}
      </md-option>
   </md-select>
</md-input-container>

Comments

0

Here is the helper function;

$scope.getIndexOf=function(arr, val, prop) {
      var l = arr.length,
        k = 0;
      for (k = 0; k < l; k = k + 1) {
        if (arr[k][prop] === val) {
          return k;
        }
      }
      return false;
    };

Example is;

$scope.Index=function(){
$scope.getIndexOf(vm.filterable_columns,"{{filterable_column.label}}","filterable_column.label")
};

You call this function in md-option's ng-change event. like this;

<md-select ng-model="visualization.filterable_columns" ng-change="drawFilters(); getIndexOf(vm.filterable_columns, {{filterable_column.label}}, filterable_column.label) " multiple="true" ng-init="index = 1">
           <md-option ng-repeat="filterable_column in vm.filterable_columns" value="{{index++}}">
                                 {{filterable_column.label}}
            </md-option>
      </md-select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.