javascript - 在 AngularJS 中保存文本区域文本

标签 javascript jquery html angularjs

我正在尝试使用 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/

相关文章:

javascript - NodeJS - 创建一个使用 Sequelize 函数的 Promise 函数

javascript - 单击按钮时触发按键

javascript - 成功函数中的数组未定义

html - Bootstrap 样式未在 asp.net gridview 中呈现并显示其他一些类

javascript - JS - Knex,将函数传递给 Transaction

javascript - 动态创建的 JQUERY 按钮默认为最后创建的元素

javascript - HTML5 可拖动 ='false' 在 Firefox 浏览器中不起作用

jquery - 从选择中排除元素

html - 如何将 flex box 元素设置为没有宽度的动画?

html - 需要帮助将表格置于 div 容器中