我知道它类似于 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
从其他范围值获取数据并将其放入文本区域:
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
范围值:
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/