[英]Add new text to div every time button is clicked
我一直在研究AngularJS,我想知道這是一種方法-不刷新頁面,每次使用AngularJS時,每次按下按鈕時都向div中添加更多文本? 我知道可以使用文本和提交按鈕來完成此操作,但是我不知道如何僅通過按鈕即可完成操作,這是一個示例。
<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>
您可以使用純JavaScript執行此操作。 請看下面的JS
function addWord() {
document.getElementById("text").innerHTML = document.getElementById("text").innerHTML + "word";
}
通過如下設置按鈕的onclick
調用函數addWord()
<button onclick="addWord()">Word</button>
使用AngularJS可以將ng-model
與ng-repeat
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.