Search code examples
angularjshtmlangularjs-filter

What is the type of "input" parameter in filter function


I have written the following custom filters

The HTML code is :

<!DOCTYPE>
<html>
    <head>
    </head>
    <body>
        <div ng-app="myApp">
            <div ng-controller="myCont">

                <div ng-repeat="b in ar2">
                    {{b}}
                </div>

                {{a}}
                {{c | myFilt}}
                <div ng-repeat="x in arr3">
                    {{x|myFilt}}
                </div>
            </div>
        </div>
        <script src="jquery-3.0.0.js"></script>
        <script src="angular.js"></script>
        <script src="angular_try.js"></script>

    </body>
</html>

And the angular js code is :

var myApp = angular.module("myApp",[])

myApp.controller("myCont",["$scope","$filter",function($scope,$filter){
$scope.a ="pro";
$scope.arr = ["abc","bcd","cdb"];
$scope.arr3 = [100,200,300];
$scope.ar2=[];
$scope.c = 10;
for(i in $scope.arr)
{
$scope.ar2[i] = $filter("uppercase")($scope.arr[i]);
}
}])


myApp.filter("myFilt",function(){
return function(input){
    return input + 20;
}
})

I wrote the above custom filter to understand angular filters .We can see that this customer filter works both on a number as well on an array. As the "input" parameter of the return function in filter takes both. But I was asked in an interview if the filter function can also take object as input . I got confused here and couldn't answer. I tried to search online but didn't get any good answer. Could someone please help me understand this ?


Solution

  • First of all, this filter would work with an array, but only if you have all numbers in it. In your example it works in an ng-repeat block because you are using the filter in the individual array numbers. Secondly, filters can take anything you pass to it as an input, even objects. All that matters is that you properly handle those cases. For example, if you simply passed an object the way your filter function works now, it would just coerce that object (null, {}, []) into a 0 and return 20 in your view template. Let's say in your controller you had the following

    $scope.c = {
      myNum: 100
    };
    

    The part where you are printing {{c | myFilt}} would show a 20 instead of what you might think it would return if it were properly handled.

    Or assume $scope.c = [100,200,300]; This would also display 20 because in JavaScript objects + numbers are coerced into a 0 or an empty string.