Trying to replace spaces with dashes using ng-model

后端 未结 3 737
攒了一身酷
攒了一身酷 2021-01-11 13:53

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 u

相关标签:
3条回答
  • 2021-01-11 14:03

    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;
                });
    
    0 讨论(0)
  • 2021-01-11 14:14

    First, you have to inject your filter in you module by adding it's name to the array :

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

    Secondly, the function of the filter have to return something. The String.prototype.replace() return a new String. so you have to return it :

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

    Edit: dfsq's answer being a lot more accurate than mine.

    0 讨论(0)
  • 2021-01-11 14:23

    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

    0 讨论(0)
提交回复
热议问题