[英]Angular JS SPA: How to Angular Controller SPA to call Angular service?
我正在嘗試使用Angular.js和Express.js創建一個Node.js應用程序。
我正在做的是用此代碼添加帶有地址的客戶名稱以列出(隨機)。
var mylist = new generic.list();
mylist.add({name:"Rohan",add:"Sec 49, Noida"});
mylist.add({name:"Sam",add:"Sec 63, Noida"});
mylist.add({name:"Jack",add:"Sec 15, Noida"});
現在我要在其中添加以下功能
Angular Controller - customerController to call an angular service
Angular Service - dataService - to call node js API (implemented earlier) using $http.
Angular View – customers.html - to display list of customers. Display the count of customers at the bottom of the SPA page.
我被困住了,請幫忙。 如何從這一步開始。
請參見有效的Plnkr示例: http ://plnkr.co/edit/YevOesJ7Jhy4wpMWiQvE?p=preview,或查看下面的代碼。
這是您的控制器
(function(){
var app = angular.module('myApp', []);
app.controller('CustomerController', CustomerController);
CustomerController.$inject = ["dataService"];
function CustomerController( dataService) {
var vm = this;
activate();
function activate() {
dataService.GetData()
.then(function(results) {
vm.data = results;
},
function(error) {})
.finally(function() {
});
}
}
})();
這是您的數據服務:您需要更改HTTP調用才能訪問node.js API,而不是list.json。
(function() {
'use strict';
angular.module('myApp')
.factory('dataService', dataService);
dataService.$inject = ['$q', '$timeout', '$http'];
function dataService($q, $timeout, $http) {
var data = [];
console.log("Number of table entries is: " + data.length);
var promise = $http.get('list.json');
promise.then(function(response) {
data = response.data;
console.log("Number of table entries is now: " + data.length);
});
return {
GetData: getData
};
function getData() {
return $q(function(resolve, reject) {
$timeout(function() {
resolve(data);
}, 3000);
});
}
}
})();
這是您的看法:
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<script data-require="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<link data-require="bootstrap@*" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://code.angularjs.org/1.4.0-beta.5/angular.js" data-semver="1.4.0-beta.5" data-require="angular.js@*"></script>
<link rel="stylesheet" href="style.css" />
<script src="controller.js"></script>
<script src="data.service.js"></script>
<script src="list.json"></script>
</head>
<body>
<div data-ng-controller="CustomerController as vm">
<table class="table table-striped table-hover">
<tbody>
<tr data-ng-repeat="record in vm.data">
<td>{{record.name}}</td>
<td>{{record.add}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.