Angular:无法找到数组的索引

时间:2016-02-01 23:29:48

标签: javascript arrays angularjs

我有一个看起来像这样的控制器:

//!>

还有一个JSON数组:

MyControllers.controller('ContentCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {

    $http.get('js/data.json').success(function(data){
        $scope.meta = data;
        $scope.whichItem = $routeParams.itemName;

        console.log($scope.whichItem);
    }).error(function() {
        alert('Unable to get back informations :-(');
    });

    $scope.title1 = [{"title":"Redhat Theme Guide"}];
    $scope.title2 = [{"title":"Debian Theme Guide"}];
}]);

我无法使用[ { "category":"category1", "link":"category1", "expand":false, "keyword":"category1, category1 online, category1 something" }, { "category":"category2", "link":"category2", "expand":false, "keyword":"category2, category2 online, category2 something" } ] 从该数组中获取数据,因为{{meta[whichItem].keyword}}变量并不代表数组的索引。它始终是一个字符串,但它应该是整数:在此示例中为whichItem0。我使用1尝试parseInt(),但没有成功。

1 个答案:

答案 0 :(得分:0)

我认为最干净的解决方案是编写一个简单的函数,通过搜索指定的类别从数组中获取项目。 我使用lo-dash非常有用,所以这是使用该库的一个例子。

JS:

$scope.getMetaDataByCategory = function(categoryId){
  return _.find($scope.meta, {category: categoryId});
};

HTML:

{{getMetaDataByCategory(whichItem).keyword}}

你也可以使用常规的for循环,但它的代码更多。