Trying to replace spaces with dashes using ng-model

Bravi picture Bravi · Dec 14, 2014 · Viewed 28.9k times · Source

I'm new to AngularJS and trying to create a simple app that will allow me to upload files to my Laravel driven website. I want the form to show me the preview of what the uploaded item will look like. So I am using ng-model to achieve this and I have stumbled upon the following:

I have an input with some basic bootstrap stylings and I am using custom brackets for AngularJS templating (because as I mentioned, I am using Laravel with its blading system). And I need to remove spaces from the input (as I type it) and replace them with dashes:

<div class="form-group"><input type="text" plaeholder="Title" name="title" class="form-control" ng-model="gnTitle" /></div>

And then I have this:

<a ng-href="/art/[[gnTitle | spaceless]]" target="_blank">[[gnTitle | lowercase]]</a>

And my app.js looks like this:

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

app.config(function($interpolateProvider){
    $interpolateProvider.startSymbol('[[').endSymbol(']]');
});

app.filter('spaceless',function(){
    return function(input){
        input.replace(' ','-');
    }
});

I get the following error: TypeError: Cannot read property 'replace' of undefined

I understand that I need to define the value before I filter it, but I'm not sure where to define it exactly. And also, if I define it, I don't want it to change my placeholder.

Answer

dfsq picture dfsq · Dec 14, 2014

There are few things missing in your filter. First of all you need to return new string. Secondary, regular expression is not correct, you should use global modifier in order to replace all space characters. Finally you also need to check if the string is defined, because initially model value can be undefined, so .replace on undefined will throw error.

All together:

app.filter('spaceless',function() {
    return function(input) {
        if (input) {
            return input.replace(/\s+/g, '-');    
        }
    }
});

Demo: http://plnkr.co/edit/5Rd1SLjvNI18MDpSEP0a?p=preview