/angularjs/

AngularJS – Custom Filter with parameter

2014-06-07 20:00:21

app.js

var app = angular.module('szalekApp', []);

app.controller('TestController', function ($scope) {
    $scope.testStr = "aa bb cc dd";
    $scope.companies = [
        {name:"Google", vote: 99},
        {name:"Macrosoft", vote: 66},
        {name:"Apple", vote: 33}
    ];
});

app.filter('addExclamationMark', function () {
    return function(input, prefix){
        if(prefix ==undefined) {
            return input + " !";
        }
        return prefix +' '+ input + " !";
    }
});

app.filter('revertWord', function () {
    return function(input){
        var arr = input.split(" ");
        var newS = "";
        arr.reverse().forEach(function(item){
            newS +=" " + item;
        });
        return newS;
    }
});

app.filter('pickCompany', function () {
    return function(input){
        var company = input[0];
        input.forEach(function (item) {
            if(company.vote < item.vote) {
                company = item;
            }
        });
        return company;
    }
});

index.html


<body ng-app='"szalekApp"'>
<section ng-controller='"TestController"'>
<!-- example -->

        {{'Lorem' | addExclamationMark}}<br/>
        {{'Lorem' | addExclamationMark:'Wow'}}<br/>
<!-- example -->
<br/>
        {{testStr}}<br/>
        {{testStr | revertWord}}<br/>
        {{testStr | revertWord | revertWord}}<br/>
<!-- example -->
<br/>
        {{testJson}}<br/>
<!-- example -->
        {{(companies | pickCompany).name}}<br/>
<!-- example -->
<div (companies="" =="" ng-init='"company' pickcompany)&quot;="" |=""></div>
        {{company.name}}<br/>
</section>
</body>