如何删除AngularJS绑定中的所有字符串空格?

Avi*_*v M 18 angularjs

我试着这样做:

<div id="{{mystring.replace(/[\s]/g, \'\')}}"></div>
Run Code Online (Sandbox Code Playgroud)

但它不起作用."mystring"是一个$scope带有字符串的对象,例如"my string is this",我想从视图中删除空格.

Cét*_*tia 49

只需创建一个专用过滤器:

angular.module('filters.stringUtils', [])

.filter('removeSpaces', [function() {
    return function(string) {
        if (!angular.isString(string)) {
            return string;
        }
        return string.replace(/[\s]/g, '');
    };
}])
Run Code Online (Sandbox Code Playgroud)

并称之为:

<div id="{{'hi there'| removeSpaces}}"></div>
Run Code Online (Sandbox Code Playgroud)


tay*_*ack 26

如果你只是需要在一两个地方,它可能更容易拆分和加入:

$scope.boundString = 'this is a string with spaces'
Run Code Online (Sandbox Code Playgroud)

你可以在模板中做到这一点:

<span>my string is: {{ boundString.split(' ').join('') }}</span>
Run Code Online (Sandbox Code Playgroud)

你会得到:

my string is: thisisastringwithoutspaces
Run Code Online (Sandbox Code Playgroud)

另一种提到的方法是正则表达式版本('g'用于全局):

<span>my string is: {{ boundString.replace(/ /g, '') }}</span>
Run Code Online (Sandbox Code Playgroud)

我想重点是你可以对表达式中的字符串做任何你想做的事情.这些示例是关于Angular脏检查的不良约定.在Angular中,绑定函数(string.replace,string.split)在绑定到模板的表达式时以不同的方式与指定值(字符串,布尔值)进行求值.必须在Angular知道是否更新DOM之前评估绑定函数的结果.这可能比大型应用程序昂贵.我建议使用另一个变量来跟踪不间隔的值:

$scope.noSpaces = $scope.boundString.replace(/ /g, '');
Run Code Online (Sandbox Code Playgroud)

HTML:

<span>{{ noSpaces }}</span>
Run Code Online (Sandbox Code Playgroud)

这样,当触发摘要循环时,Angular将检查noSpaces是否已更改,而不是评估boundString.replace(//g,'').

如果你正在重复怎么办?好问题.

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

HTML:

<ul ng-repeat="iterable in boundIterable">
    <li>{{ iterable.noSpaces }}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)


Vam*_*msi 8

提到的指令非常有效.但是,如果要删除较小文本的空格,可以使用

.split(" ").join("")
Run Code Online (Sandbox Code Playgroud)

这取代了完整的空间,而.replace(" ","")不仅仅取代了第一个空间.