2016-03-30 30 views
0

我注意到了我並不打算使用的行爲。我有一個<textarea>,如果我可以輸入一些文字,如下所示。如何在角度輸入中保留換行符

some content 
some other content 
yet another content 

當我保存這個文本轉換成JSON對象並存儲起來,我得到的是:

"value" : "some content some other content yet another content" 

另外,我有時會得到這樣的:

"value" : "some content 
some other content  
yet another content" 

我想我已經期待接收是:

"value" : "some content \n 
    some other content \n  
    yet another content" 

因此,我可以用與輸入相同的方式呈現內容。

但這似乎打破了我的JSON.parse(string)。 我在輸入模型中使用AngluarJS

編輯:

這是,如果我把我的對象在JSON驗證會發生什麼: enter image description here

+1

你是如何保存textarea的文本? –

+0

我將它保存在一個對象中。 const data = {text:$ scope.text}然後我將它發送到我的服務器,它將它存儲在重新思考數據庫中。是嗎?它有幫助嗎? –

+0

它給JavaScript中的錯誤? (如果是,那麼這是一個問題)...現在,如果_problem_是因爲你正在從控制檯複製到網站,你可以用引號替換引號''' –

回答

1

你可以嘗試用別的東西代替換行符。 如果換行符導致您的JSON.parse問題,請嘗試用<br/>之類的其他內容替換它們,當您檢索數據時,它們的行爲將類似於換行符。

您也可以嘗試在你的textareaJSON.stringify使用JSON.parse應您的textarea值轉換爲一個JSON字符串可見換行符之前。

document.getElementById("textarea-id").value.replace(/\n\r?/g, '<br />') 

OR

JSON.stringify(document.getElementById("textarea-id").value) 

console.log的在下面的例子: https://jsfiddle.net/fjj2psqj/1/

+0

我的問題是我沒有看到換行符在數據庫中只是換行而不包含\ n char –

+0

是的,新行字符不會顯示,但它存在於字符串中。如果您像上面所做的那樣進行替換,則會注意到文本區域中的新行將被替換爲
。 –

+0

好的,我會試一試 –

0
// valid JSON 
var data = { 
    "value": [ 
     "line", 
     "line", 
     "line" 
    ] 
}; 

// stringify the data to save it as text 
var dataString = JSON.stringify(data); 

// parse the string and join the array to recover line breaks 
// or iterate over values array depending on your use case 
var withNewLines = JSON.parse(dataString).value.join("\n"); 
0

您可以通過JSON.stringify發送之前運行捕獲textarea的字符串到您的服務器和JSON.parse它,然後再次在您的應用程序中使用。

$scope.doSomethingWithTextareaText = function() { 
    //assuming your textarea is bound to $scope.text 
    $scope.myObject['value'] = $scope.text; 
    $scope.myObject['stringifyValue'] = JSON.stringify($scope.text); 
    /* 
     $scope.myObject[value]: 
     some content 
     some other content 
     yet another content 
     $scope.myObject[stringifyValue]: 
     "some content\nsome other content\nyet another content" 
     JSON.parse($scope.myObject[stringifyValue]): 
     some content 
     some other content 
     yet another content 
    */ 
} 

請參閱http://jsfiddle.net/5d2oekv0/3/