I am trying to save the the text input on a textarea using AngularJS.
I need to save this each time the text is changed and store the values in a service so that I can retrieve it later to submit to the Database.
My textarea in my form.html looks as follows:
<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}}
In my controller I implement a $watch() on the ng-model as below, but this is not working. I also tried to implement a ng-change but again with no success.
$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());
};
And my service for saving the textarea text like below:
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;
}
}
}
Try This, with 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);
};
I do it in my computer and it works,
in controller:
$scope.newMessage = '';
$scope.$watch('newMessage', function(newValue, oldValue) {
if (newValue !== oldValue) {
console.log('do save staff');
}
});
in html:
<textarea class="textarea" style="width: 90%; margin-left: 5%" rows="7" maxlength="100" ng-model="newMessage" placeholder="Additional comments"></textarea>
output:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.