我有以下代码在unordered list
内显示来自mongolab的员工列表。使用ng-repeat可正确列出员工。现在我介绍了一个添加新员工的按钮。它插入了员工记录 - 但没有刷新UI中的列表。我想这是因为我没有使用ng-model。我的问题是: -
CODE
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-resource.js"></script>
<script type="text/javascript">
//defining module
var app = angular.module('myApp', ['ngResource']);
//defining factory
app.factory('employees', function ($resource) {
return $resource('https://api.mlab.com/api/1/databases/humanresource/collections/Employees',
{apiKey: 'removedmykey'}
);
});
//defining controller
app.controller('myController', function ($scope, employees)
{
$scope.empList = employees.query();
$scope.AddUser = function()
{
alert("called");
var d = new Date();
var nameVal = "Emp-"+d.toString();
var newEmployee = {
name: nameVal
}
employees.save(newEmployee);
return true;
};
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<ul>
<li ng-repeat = "objEmployee in empList" ng-class-even="'light-gray'" ng-class-odd = "'dark-gray'" >
{{objEmployee.name}}
</li>
</ul>
<input type="submit" value= "AddUser" ng-click="AddUser()" />
</div>
</body>
</html>
答案 0 :(得分:3)
ng-repeat
不需要双向绑定:它不需要保存从视图到模型的任何内容。输入字段需要双向绑定,例如:输入字段必须显示模型中的值,并在字段中键入内容必须更新模型。
您的代码没有显示添加的员工仅仅是因为您还没有将新员工添加到视图显示的员工阵列中:
$scope.AddUser = function() {
...
// create a new employee
var newEmployee = ...
// send it to the server
employees.save(newEmployee);
// add it to the array of displayed employees
$scope.empList.push(newEmployee);
};