How can I remove all string spaces in AngularJS binding?

前端 未结 7 932
南方客
南方客 2020-12-29 06:09

I try to do this:

but its not working. \"mystring\" is an object on

7条回答
  •  醉梦人生
    2020-12-29 06:55

    If you simply need it in one or two places it may be easier to split and join:

    $scope.boundString = 'this is a string with spaces'
    

    with that you could do in your template:

    my string is: {{ boundString.split(' ').join('') }}
    

    and you would get:

    my string is: thisisastringwithoutspaces
    

    another approach that has been mentioned is the regex version ('g' is for global):

    my string is: {{ boundString.replace(/ /g, '') }}
    

    I guess the point is that you can do whatever you want to a string within an expression. These examples are bad convention with respect to Angular dirty-checking. In Angular, bound functions (string.replace, string.split) get evaluated differently opposed to a specified value (string, boolean) when bound to a template's expression. The result of a bound function must be evaluated before Angular knows whether or not to update the DOM. This can be costly over a large app. I would suggest using another variable to track the un-spaced value:

    $scope.noSpaces = $scope.boundString.replace(/ /g, '');
    

    HTML:

    {{ noSpaces }}
    

    This way, when a digest loop is triggered, Angular will check if noSpaces has changed as opposed to evaluating boundString.replace(/ /g, '').

    What if you are ng-repeating? Good question.

    for (var idx = 0, idx < $scope.boundIterable.length, i++) {
        $scope.boundIterable[i].noSpaces = $scope.boundIterable[i].boundString.replace(/ /g, '');
    }
    

    HTML:

    • {{ iterable.noSpaces }}

提交回复
热议问题