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

如何删除AngularJS绑定中的所有字符串空格?,angularjs,Angularjs,我尝试这样做: <div id="{{mystring.replace(/[\s]/g, \'\')}}"></div> 但它不起作用。“mystring”是$scope上的一个对象,其字符串类似于“my string is this”,带有我要从视图中删除的空格。只需创建一个专用筛选器: angular.module('filters.stringUtils', []) .filter('removeSpaces', [function() { retu

我尝试这样做:

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


但它不起作用。“mystring”是
$scope
上的一个对象,其字符串类似于“my string is this”,带有我要从视图中删除的空格。

只需创建一个专用筛选器:

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

.filter('removeSpaces', [function() {
    return function(string) {
        if (!angular.isString(string)) {
            return string;
        }
        return string.replace(/[\s]/g, '');
    };
}])
把它叫做:

<div id="{{'hi there'| removeSpaces}}"></div>

您可以使用
replace()
将所有空格替换为空白:


如果您只是在一个或两个位置需要它,则拆分和合并可能更容易:

$scope.boundString = 'this is a string with spaces'
有了它,您可以在模板中执行以下操作:

<span>my string is: {{ boundString.split(' ').join('') }}</span>
提到的另一种方法是正则表达式版本(“g”表示全局):

HTML:

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

如果你在重复呢?好问题

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

  • {{iterable.noSpaces}}

{{{string.trim()}}


上述指令运行良好。但如果您想删除较小文本的空格,可以使用

.split(" ").join("")

这将替换完整的空格,而不像
。replace(“,”)
只替换第一个空格。

您可以使用
replace()
执行此操作:


我希望如此。

不是简单的javascript。因此,您不能假设在javascript执行上下文中工作的所有内容都将作为角度表达式工作。这似乎只替换第一个空格。您正在查找
。replace(//g',)
这将从
字符串的开头和结尾移除空格。嗨,Cétia,当我获得输入字段上的数据和显示(在编辑配置文件时)时,这工作正常。但通过使用此解决方案,字段是不可写的。请建议使用可写输入字段的解决方案。谢谢。干净、漂亮、简单!非常感谢。请补充一些解释,你是如何得出这个结果的。
removeSpaces() {
  originalText ="hi! here i'm";
  removedSpacesText = originalText.split(" ").join("");
}
$scope.noSpaces = $scope.boundString.replace(/ /g, '');
<span>{{ noSpaces }}</span>
for (var idx = 0, idx < $scope.boundIterable.length, i++) {
    $scope.boundIterable[i].noSpaces = $scope.boundIterable[i].boundString.replace(/ /g, '');
}
<ul ng-repeat="iterable in boundIterable">
    <li>{{ iterable.noSpaces }}</li>
</ul>
.split(" ").join("")
{{mystring.replace(" ","")}}
removeSpaces() {
  originalText ="hi! here i'm";
  removedSpacesText = originalText.split(" ").join("");
}