javascript angularjs 中的 textarea 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31943619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
textarea value in angularjs
提问by irom
I know it is similar to thisIn controller below I don't know how to get textarea value. In jquery I would just do $("#textarea1").val(); but can't do it here. Also if I create new model i.e.note for textarea I can refer to it as $scope.note bit still don't know what how to make assign textarea to it.
我知道这是类似于这种在控制器下面,我不知道如何让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);
};
});
Here is html
这是 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>
回答by michelem
Assign an ng-model
to it:
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>
Then you can get it from the controller with $scope.myTextArea
然后你可以从控制器获取它 $scope.myTextArea
You could use also $watch
to get data from other scope values and put into textarea:
您还可以使用$watch
从其他范围值中获取数据并放入 textarea:
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);
};
}]);
UPDATE:
更新:
You can also use ng-change
in your input text to change the myTextArea
scope value:
您还可以ng-change
在输入文本中使用来更改myTextArea
范围值:
HTML:
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>