【踩坑】angularJS 1.X版本中 ng-bind 指令多空格展示
做項目的時候遇到的問題
1、問題描述
用戶在表單某個值輸入多個空格,例如:A B,保存至服務器
在列表查詢頁面中使用bg-bind的指令單向綁定,結果展示位A B,連續的空格被替換為單個空格
2、定位分析
2.1 從用戶輸入到最終查詢展示經理太多環節,可能轉換的地方有: 輸入時的事件中,請求服務器前,http傳輸,服務器接收解析,服務器處理,服務器保存至數據庫,數據庫查詢服務,查詢服務返回,界面展示
因此逆向定位問題好些
通過Chrome中network看到服務器返回的數據帶有多個空格,查看html元素,元素代碼中是由多個空格,
初步判定是由於類似html直接賦值給dom元素,html默認會把連續空格展示為1個空格
2.2 分析代碼走向,在angular 1.4.8中 ngBindDirective 代碼如下
這裏是采用textContent方法
textContent的特點在文章下方的參考中已經指出:先將ASCII實體對應的字符(<、>、&、‘和")轉換為實體名,然後把處理後的值賦予給innerHTML屬性。
var ngBindDirective = [‘$compile‘, function($compile) {
return {
restrict: ‘AC‘,
compile: function ngBindCompile(templateElement) {
$compile.$$addBindingClass(templateElement);
return function ngBindLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.ngBind);
element = element[0];
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
element.textContent = isUndefined(value) ? ‘‘ : value;
});
};
}
};
}];
3、解決
3.1 嘗試直接替換value中的空格 element.textContent = isUndefined(value) ? ‘‘ : value.replace(/[ ]/g," ");
 會被保留在html中,這和以前常用的jquery的html()或者innerHtml不一樣
3.2 替換後的value以innerHtml的方法放到DOM對象中
element.textContent = isUndefined(value) ? ‘‘ : value;
element.innerHTML = (element.textContent + ‘‘).replace(/[ ]/g," ");
OK ,搞定,這裏入戲修改是否合適還不太清除。基於我們項目目前的情況1、嚴格使用ng-bind,2 使用$sce 3、數據在Service有編碼轉碼處理,目前還沒有發現BUG,但是在通用場景下這樣改是否合適? 歡迎大家補充
參考:JS魔法堂:被玩壞的innerHTML、innerText、textContent和value屬性
【踩坑】angularJS 1.X版本中 ng-bind 指令多空格展示