[英]Saving textarea text in AngularJS
我正在嘗試使用AngularJS將文本輸入保存在textarea上。
每次更改文本時,我都需要保存此內容,並將值存儲在服務中,以便以后可以檢索它以提交給數據庫。
我的form.html中的 textarea如下所示:
<textarea class="textarea" style="width: 90%; margin-left: 5%" rows="7" maxlength="100" ng-model="newMessage" placeholder="Additional comments"></textarea>
<!-- This isnt displaying anything -->
{{newMessage}}
<!-- This isnt displaying anything -->
{{myTextArea}}
在我的控制器中,我在ng-model上實現了一個$ watch(),如下所示,但這不起作用。 我也嘗試實施ng-change,但沒有成功。
$scope.$watch("newMessage", function (newVal, oldVal)
{
console.log("Getting here..."); // Getting here
if (newVal !== oldVal)
{
// This block is never executed
$scope.myTextArea = "This is new values: " + newVal;
// Save the new textarea text to service
save($scope.myTextArea);
}
});
$scope.save = function ()
{
// This block never executed
console.log("sharedProperties.setAdditionalCommentsText(): ");
sharedProperties.setAdditionalCommentsText($scope.myTextArea);
console.log("sharedProperties.getAdditionalCommentsText: " + sharedProperties.getAdditionalCommentsText());
};
和我的服務,用於保存textarea文本,如下所示:
app.service('sharedProperties', function()
{
// Initialise the Variables
var additionalCommentsText = "";
return
{
// Get and set the Additional Comments Text
getAdditionalCommentsText: function()
{
return additionalCommentsText;
},
setAdditionalCommentsText: function(value)
{
additionalCommentsText = value;
}
}
}
試試這個,用ng-change
<textarea class="textarea" style="width: 90%; margin-left: 5%" rows="7" maxlength="100" ng-model="newMessage" ng-change="save(newMessage);" placeholder="Additional comments"></textarea>
JS
$scope.save = function (message) {
console.log(message);
};
我在電腦上完成了工作,
在控制器中:
$scope.newMessage = '';
$scope.$watch('newMessage', function(newValue, oldValue) {
if (newValue !== oldValue) {
console.log('do save staff');
}
});
在html中:
<textarea class="textarea" style="width: 90%; margin-left: 5%" rows="7" maxlength="100" ng-model="newMessage" placeholder="Additional comments"></textarea>
輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.