Search code examples
javascriptangularjstypeerrorangular-filters

AngularJS TypeError


Getting a TypeError: undefined is not a function error. The code is meant to filter a list by the tags that it contains. I had the code working for a single tag but now that the query is an array of tags it's not working.

angular.module('myapp', [])
    .controller('myctrl', function($scope, $http) {
        $scope.formData = {};
        $scope.formData.query = "";    

        $scope.formData.list = [{"Tags":["a", "b", "c"]}, {"Tags":["a", "b"]}, {"Tags":["b", "c"]}]    

        $scope.filterTags = function(query){
            return function(elem){
                query = query.split(",");    

                for(i in query){    

                    if(elem.Tags.indexOf(query[i]) == -1){
                        return false;
                    }

                }    

                return true;
            };

        }    

    });

And the template.

<div ng-app="myapp" ng-controller="myctrl">
    <input type='text' ng-model='formData.query' />
    <ul>
        <li ng-repeat='item in formData.list | filter:filterTags(formData.query)'>{{item.Tags}}</li>
    </ul>
</div>

Solution

  • You just have one line in the wrong place. The line is:

    query = query.split(",");
    

    It should be before the return function(elem) line so you don't split it every time. But more importantly, it's because that line changes query from being a string to being an array. And arrays don't have a .split() method. Hence the "undefined is not a function" error. :-)

    Updated JS code:

    angular.module('myapp', [])
        .controller('myctrl', function($scope, $http) {
            $scope.formData = {};
            $scope.formData.query = "";    
    
            $scope.formData.list = [{"Tags":["a","b","c"]},{"Tags":["a","b"]},{"Tags":["b","c"]}]    
    
            $scope.filterTags = function(query){
                query = query.split(",");    
                return function(elem){
                    for(var i in query){    
                        if(elem.Tags.indexOf(query[i]) == -1){
                            return false;
                        }
                    }    
                    return true;
                };
            }    
        });