我正在玩一些代码,我在按钮上放置了一个事件,我注意到它运行了ng-repeat,即使我从未指示程序这样做。当我单击添加按钮时,它在成员数组中添加对象,但由于我使用角度来显示它,我不明白为什么它在视图中添加它。按钮上的点击事件已添加,它开始发生。我完全不理解它,因为它只是一个错误"。
<!DOCTYPE html>
<html lang="en" ng-app="module">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<style>
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
</head>
<body ng-controller="controller">
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Job</th>
</tr>
<tr ng-repeat= "ob in members">
<td>{{ob.name}}</td>
<td>{{ob.age}}</td>
<td>{{ob.job}}</td>
</tr>
</table>
<p> There are {{numMembers}} in the company</p>
<input type="text" placeholder="Name">
<input type="text" placeholder="age">
<input type="text" placeholder="Job">
<button type="submit" id= "button" ng-click="numMembers">Add</button>
<script>
"use strict"
var inputs = document.querySelectorAll('input');
var submit = document.getElementById('button');
const members = [];
class Register {
constructor(name,age,job){
this.name = name;
this.age = age;
this.job = job;
}
addMember(){
members.push({ name: this.name,
age: this.age,
job: this.job});
}
static membersNum(){
return members.length;
}
}
const memberOne = new Register("georges tchianga","21","web developer");
const memberTwo = new Register("john lenon","41","Math teacher");
const memberThree = new Register("john okorozo","22","Nurse");
const memberFour = new Register("Adam simons","24","Doctor");
const memberFive = new Register("selena roski","28","Singer");
memberOne.addMember();
memberTwo.addMember();
memberThree.addMember();
memberFour.addMember();
memberFive.addMember();
submit.addEventListener("click",function(e) {
e.preventDefault();
var name = inputs[0].value;
var age = inputs[1].value;
var job = inputs[2].value;
const AddingMembers = new Register(name,age,job);
AddingMembers.addMember();
console.log(members);
})
var modul = angular.module("module",[]);
modul.controller("controller",function($scope) {
$scope.members = members;
$scope.numMembers = Register.membersNum();
})
</script>
</body>
</html>
答案 0 :(得分:0)
ng-repeat在模型上有一个内部的监视,每当你修改模型时(即在模型中添加,更新或删除),它会重复并重复渲染。< / p>
正如您所说,按钮上的点击事件会更改ng-repeat模型并将值推入其中。这就是ng-repeat将在视图中添加新值的原因。