[英]Retrieving JSON data from API using AngularJS
我正在嘗試從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');
};
})
調節器
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文件訪問所有數據。 它可以幫助你打電話給休息服務。 檢查這個例子
數據/ branchList.json
[
{
"branch_id": 1,
"branch_name": "Mummbai",
"branch_address": "India"
},
{
"branch_id": 2,
"branch_name": "New York",
"branch_address": "US"
}
]
調節器
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.