angularjs中的textarea值

时间:2015-08-11 13:49:00

标签: javascript jquery html angularjs

我知道它与this类似。在下面的控制器中,我不知道如何获得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>

1 个答案:

答案 0 :(得分:4)

为其分配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>