2016-08-02 65 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]); 
});