gpt4 book ai didi

javascript - AngularJS SPA : How to Angular Controller SPA to call Angular service?

转载 作者:行者123 更新时间:2023-12-03 08:41:20 26 4
gpt4 key购买 nike

我正在尝试使用 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 ,或查看下面的代码。

这是你的 Controller

(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>

关于javascript - AngularJS SPA : How to Angular Controller SPA to call Angular service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33045072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com