我正在创建具有Angular的Web API。我在HTML代码中遇到了问题。如果我只是调用Web API,我会获取所需的数据,但是当我尝试在HTML中打印出来时,我不会得到结果。请在下面查看我的代码。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Angular CRUD</title>
<link href="Content/bootstrap.css" rel="stylesheet"/>
<script src="Scripts/angular.js"></script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/bootstrap.js"></script>
<script>
var app = angular.module('myApp', [])
app.controller("EmployeeCtrl", function ($scope, $http) {
getEmployees();
var getEmployees = function () {
alert("SDFS");
$http.get('/api/Employee')
.then(function (response) {
$scope.Employee = response.data
},
function () {
alert("Error in retrieving data");
})
}
})
</script>
</head>
<body ng-app="myApp" ng-contoller="EmployeeCtrl">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Employee ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Employee Code</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in Employee">
<td>{{item.EmployeeId}}</td>
<td>{{item.FirstName}}</td>
<td>{{item.LastName}}</td>
<td>{{item.EmployeeCode}}</td>
<td>{{item.Position}}</td>
<td>{{item.Office}}</td>
</tr>
</tbody>
</table>
</body>
</html>
您会注意到我什至创建了一个警报以检查是否调用了该功能,但显然没有调用该功能。你能帮忙吗?谢谢。
您的代码有两个问题:
- 您拼写错误的
ng-controller
。 - 创建函数作为变量即
var funcName = function () { ... }
时,您无法在定义之前使用该函数。将其更改为function getEmployees () { ... }
解决这些问题,它将起作用!
js代码按行执行行,请在声明之前调用函数尝试此代码而不是您的控制器:
<script>
var app = angular.module('myApp', [])
app.controller("EmployeeCtrl", function ($scope, $http) {
getEmployees();
var getEmployees=function() {
alert("SDFS");
$http.get('/api/Employee')
.then(function(response) {
$scope.Employee = response.data
},
function() {
alert("Error in retrieving data");
})
}
})
</script>