javascript - AngularJS 中的文本区域值

标签 javascript jquery html angularjs

我知道它类似于 this在下面的 Controller 中我不知道如何获取文本区域值。在 jquery 中我只会做 $("#textarea1").val();但在这里做不到。另外,如果我为 textarea 创建新模型,即 note,我可以将其称为 $scope。note 位仍然不知道如何将 textarea 分配给它。

var app = angular.module("angularApp", []).controller("myConfigGenCtrl", function($scope) {
    $scope.textarea1 ="";
    $scope.clear = function() {
        $scope.textarea1 = "";
    };
    $scope.save  = function(data, filename) {
        data = $scope.textarea1;
        var blob = new Blob([data], {type: "text/plain;charset=utf-8"});
        filename = "textarea.txt";
        console.log($scope.textarea1);
        saveAs(blob, filename);
    };
});

这里是html

<body ng-app="angularApp">
    <div ng-controller="myConfigGenCtrl">
        <form name="myform">
            <input type="text" ng-model="message1"/>
            <input type="text" ng-model="message2"/>
        </form>

        <p>
            <textarea id="textarea1" cols="80" rows="10">
                This is {{message1}} in 1st line
                This is {{message2}} in lastst line
            </textarea>
        </p>
        <p>
            <button ng-click="save()">Save</button>
            <button ng-click="clear()">Clear</button>
        </p>
    </div>
</body>

最佳答案

为其分配一个ng-model:

<p><textarea id="textarea1" cols="80" rows="10" ng-model="myTextArea">
  This is {{message1}} in 1st line
  This is {{message2}} in lastst line
</textarea></p>

然后你可以使用$scope.myTextArea从 Controller 获取它

您还可以使用 $watch 从其他范围值获取数据并将其放入文本区域:

JSFiddle

angular.module('myApp', [])
    .controller('dummy', ['$scope', function ($scope) {

    $scope.$watch("message1", function (newVal, oldVal) {
        if (newVal !== oldVal) {
            $scope.myTextArea = "This is "+newVal+" in 1st line";
        }
    });

    $scope.save = function () {
        console.log($scope.myTextArea);
    };
}]);

更新:

您还可以在输入文本中使用 ng-change 来更改 myTextArea 范围值:

JSFiddle

HTML:

<input type="text" ng-model="message1" ng-change="myTextArea = message1 + message2" />
<input type="text" ng-model="message2" ng-change="myTextArea = message1 + message2" />
<p>
    <textarea id="textarea1" cols="80" rows="10" ng-model="myTextArea" ></textarea>
</p>

关于javascript - AngularJS 中的文本区域值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31943619/

相关文章:

javascript - Gmail API-gapi 未定义node.js

html - 我可以单独使用 CSS 使我的标题字体大小取决于对象的宽度吗?

html - z 索引为 -1 的元素位于祖 parent 的 div 之下

javascript - 选择后模糊()/焦点()

javascript - 不能在新函数或语法中使用前一个函数的变量?

javascript - 点击复制段落内容

javascript - 将变量与循环结合起来

jquery - Kendo UI 日期选择器无法清除之前的最小和最大日期

javascript - ID 未提交查询

jquery - 在ajax表单提交来自ckeditor textarea的值之后,不通过post发送