Search code examples
javascriptangularjsjsonindexingangularjs-ng-options

ng-options: How to access to position (index) in an object which has no index in key or value


I have a JSON obj. as below:

[
   {"Title":"x", "Type":"y", "Desc":"First Description"},
   {"Title":"r", "Type":"q", "Desc":"Second Description"}
]

I want to have a drop-down including Titles in this obj (using ng-options). Then, I want to use the the Index of selected Title in the object. (Imagine the object will be used as array (called myArray), as what user194715 answered here)
for example:

var type = myArray[selectedIndex].Type;
var description= myArray[selectedIndex].Desc;

How can I access to the index in this case?


Solution

  • try like this

    var app = angular.module("app",  []);
    
    app.controller('mainCtrl', function($scope){
      $scope.myArray =
            [
              {"Title":"x", "Type":"y", "Desc":"First Description"},
              {"Title":"r", "Type":"q", "Desc":"Second Description"}
            ];
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="app" ng-controller="mainCtrl">
        <select ng-model="select" ng-options="key as value.Title for (key,value) in myArray">
       </select>
     <span>{{myArray[select].Type}}</span>
     <span>{{myArray[select].Desc}}</span>
    </div>