xenish
xenish

Reputation: 1424

Custom filter not working angular js

I am creating a custom filter in angular js this is my html,

<div class="box-body">

<div class="form-group">
    <label>Page-Title:</label>
    <input type="text" required value="" data-ng-model="title" name="page_title" class="form-control" id="" placeholder="Enter Page Title">                     
</div>

<div class="form-group">
    <label>Page-Alias:</label>
    <input type="text" value="@{{ title | replaceSpace}}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">
</div>

This is my angular js code

var app = angular.module('CustomAngular', []);
app.controller('CustomCtrl', function ($scope) {
    app.filter('replaceSpace', function () {
        return function (input) {
            return input.replace(/ /g, '-').toLowerCase();
        };
    });
});

The filter is not working and also I get error in the console.

Error: [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=slugifyFilterProvider%20%3C-%20slugifyFilter
    at Error (<anonymous>)

If I use filter: infront of the filter name I donot get any errors in console but it's still not working.

<input type="text" value="@{{ title | filter:replaceSpace }}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">

Upvotes: 0

Views: 909

Answers (2)

maurycy
maurycy

Reputation: 8465

You should define filter outside of controller and not use filter: as it has different meaning, that's the correct way to use your filter

<input type="text" value="@{{ title | replaceSpace }}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">

although you should either initialize model by $scope.title = '' or place a check in your filter to run replace only when input is defined, otherwise you will get JS errors

filter: is used to filter the array from model, and when you pass another filter to it it does nothing

Upvotes: 2

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66991

You don't put filters inside of a controller, put it after your var app line. It's a separate thing just like controllers / directives / etc.

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

// Here's where it goes
// Also now any/all controllers can use it!

app.filter('replaceSpace', function () {
    return function (input) {
        return input.replace(/ /g, '-').toLowerCase();
    };
});

app.controller('CustomCtrl', function ($scope) {

});

Upvotes: 3

Related Questions