我试图从 Web API 获取数据并将其显示在表格中,但它不起作用。 我是 angularjs 的新手,我编写了简单的程序来从 Web API 获取数据并显示在表中。但我无法获取数据。
模块
var app = angular.module("myApp", []);
服务
app.service("myService", function ($http) {
//get All Eployee
this.getEmployees = function () {
return $http.get('http://apidemo.gouptechnologies.com/api/admin');
};
})
Controller
app.controller("myCntrl", function ($scope, myService) {
$scope.divEmployee = false;
GetAllEmployee();
function GetAllEmployee() {
alert('home');
var getData = myService.getEmployees();
getData.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('Error in getting records');
});
}
});
JS代码包含在HTML文件的head标签中。
HTML 正文
<body>
<div ng-app="myApp" ng-controller="myCntrl">
<ul>
<li ng-repeat="x in employees">
{{ x.username + ', ' + x.password }}
</li>
</ul>
</div>
</body>
API URL是合法的。 谢谢。
最佳答案
以 "data/branchList.json" 目录中的 json 文件为例,我尝试使用 $http
访问 json 文件中的所有数据。
它也可以帮助您调用休息服务。检查这个例子
data/branchList.json
[
{
"branch_id": 1,
"branch_name": "Mummbai",
"branch_address": "India"
},
{
"branch_id": 2,
"branch_name": "New York",
"branch_address": "US"
}
]
Controller
angular.module('myApp')
.controller('myCntrl', ['$http', '$state', function ($http, $state) {
'use strict';
var vm = this;
function init(){
vm.branchs = '';
loadBranch();
}
init();
function loadBranch(){
$http.get('data/branchList.json').success(function(response){
vm.branchs = response;
})
}
}]);
在此示例中,我将所有数据存储在 vm.branches
变量中,您可以在 html
页面中使用此变量
HTML
<li class="col-sm-6" ng-repeat = "branch in vm.branchs">
<strong>{{branch.branch_name}}</strong>
<span>{{branch.branch_address}}</span>
</li>
关于javascript - 使用 AngularJS 从 API 检索 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894433/