我正在尝试使用 AngularJS 将文本输入保存在文本区域中。
每次更改文本时,我都需要保存此内容并将值存储在服务中,以便稍后检索它以提交到数据库。
我的 form.html 中的文本区域如下所示:
<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}}
在我的 Controller 中,我在 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());
};
我的服务用于保存文本区域文本,如下所示:
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);
};
关于javascript - 在 AngularJS 中保存文本区域文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37132681/