Javascript 每次单击按钮时向div添加新文本
我一直在研究AngularJS,我想知道有一种方法——在不刷新页面的情况下,每次按下按钮时,使用AngularJS向div添加更多文本?我知道这可以通过文本和提交按钮来实现,但我不知道如何通过按钮来实现,下面是一个例子Javascript 每次单击按钮时向div添加新文本,javascript,html,angularjs,Javascript,Html,Angularjs,我一直在研究AngularJS,我想知道有一种方法——在不刷新页面的情况下,每次按下按钮时,使用AngularJS向div添加更多文本?我知道这可以通过文本和提交按钮来实现,但我不知道如何通过按钮来实现,下面是一个例子 <button>Word</button> <!-- Every time this is clicked, add 'word' to the div 'text' without refreshing --> <div id="te
<button>Word</button> <!-- Every time this is clicked, add 'word' to the div 'text' without refreshing -->
<div id="text" class="text">
<!-- Write word here as many times as the button is pressed -->
</div>
Word
看到这个了吗
您可以使用纯JavaScript实现这一点。请看下面的JS
function addWord() {
document.getElementById("text").innerHTML = document.getElementById("text").innerHTML + "word";
}
通过如下设置按钮的onclick
,调用函数addWord()
<button onclick="addWord()">Word</button>
Word
使用AngularJS您可以使用ng模型
和ng重复
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl',函数($scope){
$scope.data={
案文:[]
}
$scope.addText=函数(文本){
$scope.data.text.push(文本)
}
});
添加文本
{{text}}
请在您的问题中添加更多细节。到目前为止你试过什么?创建的jsfiddle
中的javascript字段为空。您希望使用哪个版本的angular(1/2)?
var myApp = angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope) {
$scope.data = {
texts : []
}
$scope.addText = function(text){
$scope.data.texts.push(text)
}
});
<div ng-controller="myCtrl">
<button ng-click="addText(data.text)">Add text</button>
<input type="text" ng-model="data.text">
<div ng-repeat="text in data.texts">{{text}}</div>
</div>