我正在尝试使用ng-repeat将textarea打印出列表。相反,我有几个textareas,列表中各有一个项目。我明白为什么它不起作用,但无法弄清楚要改变什么来获得我想要的结果。这是我的代码
<!DOCTYPE html>
<html lang="en" ng-app = 'app'>
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src = 'bower_components/angular/angular.js'>
</script>
<script>
var app = angular.module('app', []);
app.controller('myController', ['$scope', function($scope){
//printController will show the current $scope
$scope.list = []
$scope.submit = function(){
console.log($scope.myModel)
if($scope.myModel){
$scope.list.push(this.myModel);
$scope.myModel = ''
}
}
}]);
</script>
</head>
<body>
<div ng-controller = "myController" id = "myController">
<label>Favorite Food </label>
<input type="text" ng-model = 'myModel'>
<button ng-click="submit()">
<label>Favorite Food:</label>
</button>
<div id ='model' ng-if = "myModel">
<label>Currently Typing: </label>
<span ng-bind='myModel'>
</span>
</div>
<textarea ng-repeat="elements in list">{{elements}}</textarea>
</div>
</body>
</html>
这就是我想要的
答案 0 :(得分:3)
一种方法是在控制器中有一个函数返回由换行符连接的数组。
$scope.textAreaValues = function(){
return $scope.list.join('\n');
}
然后在HTML模板中调用它
<textarea>{{ textAreaValues() }}</textarea>
答案 1 :(得分:0)
不幸的是,你不能像这样使用ng-repeat
,因为它会创建你添加它的元素的实例。但是,您可以通过使用过滤器来实现您的目标:
.filter("displayFilter", function(){
return function(items){
var result = '';
angular.forEach(items, function(item, index){
result += item;
// only add a newline if we have more items to add
if(index !== items.length - 1){
result += '\n';
}
});
return result;
}
})
然后在textarea中使用该过滤器:
<textarea>{{elements | displayFilter}}</textarea>
答案 2 :(得分:0)
请运行我的代码片段以实现目标。
var app = angular.module('app', []);
app.controller('myController', ['$scope', function($scope){
//printController will show the current $scope
$scope.list = [];
$scope.submit = function(){
console.log($scope.myModel)
if($scope.myModel){
$scope.list.push($scope.myModel);
$scope.myModel = '';
}
}
$scope.$watch(
function(){return $scope.list.join("\n");},
function(newVal,oldVal){
$scope.allTexts = newVal;
}
);
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller = "myController" id = "myController">
<label>Favorite Food </label>
<input type="text" ng-model = 'myModel'>
<button ng-click="submit()">
<label>Favorite Food:</label>
</button>
<div id ='model' ng-if = "myModel">
<label>Currently Typing: </label>
<span ng-bind='myModel'>
</span>
</div>
<textarea ng-model="allTexts"></textarea>
</div>
</body>
答案 3 :(得分:-1)
如果我正确理解你的问题。您希望在textarea中打印项目列表。您应该从
更改以下代码<textarea ng-repeat="elements in list">{{elements}}</textarea>
到
<input type="text" ng-model="list" ng-disabled="true"></input>
不要尝试创建textarea然后在其中打印值,而是创建textarea(输入)并将其绑定到包含项目列表的模型。
我附上了一个jsFiddle。