2016-08-02 51 views
1

我想用方法過濾器Angular.JS並採取第一個元素名稱遊戲篩選方法 - Angular.JS

$scope.example = [ 
     {model : "Games", id : "1"}, 
     {model : "Pictures", id : "2"}, 
     {model : "Cars", id : "3"}, 
     {model : "Games", id : "4"}, 
    ]; 
在HTML

很容易藉此但JS我不`噸知道如何:(

$scope.example.filter(model:Games).TakeFirst()??? 
+3

創建自定義過濾器,將返回'返回arr.find(O => o.model ===名);' – Tushar

+0

@Tushar是它'工作正確的 - 把這個作爲答案:) –

回答

2

要使用過濾器在你的控制器,你應該注入$filter之後,你可以使用[0]獲得第一個元素

例子。

var myApp = angular.module('myApp',[]); 
myApp.controller('MyCtrl', function($scope,$filter) { 
    $scope.example = [ 
     {model : "Games", id : "1"}, 
     {model : "Pictures", id : "2"}, 
     {model : "Cars", id : "3"}, 
     {model : "Games", id : "4"}, 
    ]; 
    console.log($filter('filter')($scope.example, { model: "Games" })[0]); 
});