Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to replace spaces with dashes using ng-model

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.

like image 521
Bravi Avatar asked Dec 14 '14 21:12

Bravi


2 Answers

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

like image 98
dfsq Avatar answered Oct 22 '22 12:10

dfsq


Bravi just try this filter for eaxample {{X | replaceSpaceToDash}}

 app.filter('replaceSpaceToDash', function(){
                var replaceSpaceToDash= function( input ){

                        var words = input.split( ' ' );
                         for ( var i = 0, len = words.length; i < len; i++ )
                             words[i] = words[i].charAt( 0 ) + words[i].slice( 1 );
                         return words.join( '-' );
                     };
                     return replaceSpaceToDash;
            });
like image 26
Pradip Wawge Avatar answered Oct 22 '22 13:10

Pradip Wawge