在AngularJS中保存textarea文本

时间:2016-05-10 08:08:42

标签: javascript jquery html 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;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

使用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);
};

答案 1 :(得分:1)

我在我的电脑上完成它并且有效,

控制器中的

$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>

输出:

enter image description here