繁体   English   中英

angularjs中的textarea值

[英]textarea value in angularjs

我知道它与类似。在下面的控制器中,我不知道如何获取textarea值。 在jQuery中,我只想做$(“#textarea1”)。val(); 但不能在这里做。 另外,如果我为textarea创建新模型ienote,我可以将其称为$ 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从控制器中获取它

您还可以使用$watch从其他范围值获取数据并放入textarea中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM