Rafael - Developer Rafael - Developer - 4 months ago 10
Javascript Question

Filter method - Angular.JS

I would like to use method filter in Angular.JS and take first element with name Games

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


in HTML is very easy take this but in JS I don`t know how :(

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

Answer

To use filters in your controller you should inject $filter. After that, you can get first element using [0].

Example;

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]);
});