如何在控制器中获取数组项的索引位置,传递angularjs中的值

uma*_*uma 12 angularjs angularjs-scope

我有一个包含值列表的数组.

 [Object { id="5", country="UAE"}, Object { id="4", country="India"}]
Run Code Online (Sandbox Code Playgroud)

我想根据id中的值获取数组项的索引.如何在angularJS控制器中获取值为id = 4的数组项的索引位置?

jin*_*gel 23

angularjs方式(使用$ filter)将是这样的

app.controller('MainCtrl', ['$scope', '$filter', function($scope, $filter) {

    //array
    var items = [{  id: "5", country: "UAE" }, { id: "4",  country: "India" }];

    //search value
    var id2Search = "4";

    //filter the array
    var foundItem = $filter('filter')(items, { id: id2Search  }, true)[0];

    //get the index
    var index = items.indexOf(foundItem );
}]);
Run Code Online (Sandbox Code Playgroud)


Ana*_*and 10

这不是angularjs特定问题,而是正常的javascript.只需循环并返回索引

var list =  [{ id="5", country="UAE"}, { id="4", country="India"}];

for (var i = 0; i < list.length ; i++) {
        if (list[i][id] === 4) {
            return i;
        }
 }
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过使其在接受值和属性名称的数组上运行来使其成为通用的

Array.prototype.getIndexOfObject = function(prop, value){
   for (var i = 0; i < this.length ; i++) {
            if (this[i][prop] === value) {
                return i;
            }
     }
}
Run Code Online (Sandbox Code Playgroud)