我嘗試這樣做:如何刪除AngularJS綁定中的所有字符串空間?
<div id="{{mystring.replace(/[\s]/g, \'\')}}"></div>
,但它不工作。 「mystring」是$scope
上的一個對象,帶有「我的字符串是this」字符串,並帶有要從視圖中刪除的空格。
我嘗試這樣做:如何刪除AngularJS綁定中的所有字符串空間?
<div id="{{mystring.replace(/[\s]/g, \'\')}}"></div>
,但它不工作。 「mystring」是$scope
上的一個對象,帶有「我的字符串是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>
嗨Cétia,當我獲得數據並在輸入欄顯示時(編輯配置文件時),這項工作正常。但通過使用此解決方案字段是不可寫的。請建議具有可寫入輸入字段的解決方案。謝謝。 – 2017-07-05 12:39:59
如果單純需要在一個或兩個地方拆分和連接:
$scope.boundString = 'this is a string with spaces'
用,你可以在你的模板做:
<span>my string is: {{ boundString.split(' ').join('') }}</span>
,你會得到:
my string is: thisisastringwithoutspaces
已經提到的另一種方法是正則表達式版本( 'G' 是對於全球):
<span>my string is: {{ boundString.replace(/ /g, '') }}</span>
我想點我你可以在表達式中做任何你想要的字符串。這些示例在角度髒檢查方面是不好的慣例。在Angular中,當綁定到模板表達式時,綁定函數(string.replace,string.split)的計算方式與指定值(字符串,布爾值)不同。在Angular知道是否更新DOM之前,必須先評估綁定函數的結果。這可能是一個大型應用程序的代價。我會建議使用另一個變量來跟蹤未間隔值:
$scope.noSpaces = $scope.boundString.replace(/ /g, '');
HTML:
<span>{{ noSpaces }}</span>
這樣,當一個消化循環被觸發,角將檢查noSpaces,而不是改變評估boundString.replace(//g,'')。
如果你是重複的?好問題。
for (var idx = 0, idx < $scope.boundIterable.length, i++) {
$scope.boundIterable[i].noSpaces = $scope.boundIterable[i].boundString.replace(/ /g, '');
}
HTML:
<ul ng-repeat="iterable in boundIterable">
<li>{{ iterable.noSpaces }}</li>
</ul>
上述指令工作得很好。但是,如果你想刪除的空間較小的文本,你可以使用
.split(" ").join("")
這取代了完整的空間不像.replace(" ","")
這僅替換第一空間。
乾淨,好看又簡單!謝謝! – 2018-02-15 10:03:45
您可以通過使用replace()
做到這一點:
{{mystring.replace(" ","")}}
就是這樣我也希望如此。
[Angular expressions](https://docs.angularjs.org/guide/expression)不是簡單的javascript。所以你不能假定在javascript執行上下文中的所有東西都可以作爲一個角度表達式來工作。 – Yoshi 2014-10-07 09:46:42