I am new to AngularJS, I have two text boxes namely Name,Age. I want to add the name and age entered in the text box to HTML table. When I use the below code it adds the row to the table for the first time and if I try to add more row, it modifies the last row added in the table. I'm passing the employee object here.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Scripts/angular.min.js" type="text/javascript"></script>
<link href="Styles/StyleSheet.css" rel="stylesheet" type="text/css" />
<title></title>
<script>
var myApp = angular.module("myApp", []);
var myController = myApp.controller("myController", function ($scope) {
$scope.employees = [
{ name: "Joe", age: "20" },
{ name: "Sam", age: "27" }
];
$scope.addEmp = function (emp) {
$scope.employees.push(emp);
}
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<table>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr ng-repeat="employee in employees">
<td>{{employee.name}}</td>
<td>{{employee.age}}</td>
</tr>
</table>
Name<input id="Name" type="text" ng-model="emp.name"/>
Age<input id="Age" type="text" ng-model="emp.age"/>
<input type="button" ng-click="addEmp(emp)" />
</div>
</body>
</html>
But when I pass the name and age separately as given below it works fine. Why this is happening?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Scripts/angular.min.js" type="text/javascript"></script>
<link href="Styles/StyleSheet.css" rel="stylesheet" type="text/css" />
<title></title>
<script>
var myApp = angular.module("myApp", []);
var myController = myApp.controller("myController", function ($scope) {
$scope.employees = [
{ name: "Joe", age: "20" },
{ name: "Sam", age: "27" }
];
$scope.addEmp = function (name, age) {
$scope.employees.push({name:name,age:age});
}
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<table>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr ng-repeat="employee in employees">
<td>{{employee.name}}</td>
<td>{{employee.age}}</td>
</tr>
</table>
Name<input id="Name" type="text" ng-model="name"/>
Age<input id="Age" type="text" ng-model="age"/>
<input type="button" ng-click="addEmp(name,age)" />
</div>
</body>
</html>