我是AngularJS编程的新手,我写了一些代码,没有任何错误,在控制台中它提供了我想要的内容,但未显示在网页上。我正在尝试进行2个HTTP调用,进行获取和发布,获取向我展示列表中所有元素,并在此列表中添加元素。它们正在工作,但是当我尝试列出所有元素时,它什么也没给我显示:(
这是我的代码:
dataContext.js
(function () {
'use strict';
angular.module('app').service('dataContext', ['httpService', function (httpService) {
var service = {
getAllUsers: getAllUsers,
addUser: addUser,
saveMessage: saveMessage
};
function getAllUsers() {
return httpService.get("api/users");
}
function addUser(name) {
return httpService.post("api/users", { name: name });
}
dashboard.js
(function () {
'use strict';
angular.module('app').controller("dashboardController", ['dataContext', function (dataContext) {
var vm = this;
vm.getUser = function () {
dataContext.getAllUsers().then(
function (response) {
alert(response.data[0].Name);
},
function (error) {
console.log(error);
}
);
};
vm.postUser = function () {
dataContext.addUser(vm.username).then(
function (response) {
alert("User, " + vm.username + " was added!");
},
function (error) {
console.log(error);
}
);
};
})();
httpService.js
(function () {
'use strict';
angular.module('app').service('httpService', ['$http', '$q', 'backendConfig', function ($http, $q, backendConfig) {
var service = {
get: get,
post: post
};
function get(path) {
var deferred = $q.defer();
$http.get(backendConfig.url + path).then(
function (response) {
deferred.resolve(response);
},
function (err, status) {
deferred.reject(err);
}
);
return deferred.promise;
}
function post(path, data) {
var deferred = $q.defer();
$http.post(backendConfig.url + path, data).then(
function (response) {
deferred.resolve(response);
},
function (err, status) {
deferred.reject(err);
}
);
return deferred.promise;
}
return service;
}]);})();
和我的 dashboard.html
<div ng-controller="dashboardController as vm">
<button ng-click="vm.getUser()">Get</button>
<button ng-click="vm.postUser()">Post</button>
<input ng-model="vm.username" />
<ul>
<li ng-repeat="obj in vm.users">{{obj.Name}}</li>
</ul>
列表的名称是users,我有一个类Users,带有字符串Name,一切都应该正确,但我不知道为什么它不起作用。任何帮助都会很棒
谢谢
答案 0 :(得分:1)
替换
alert(response.data[0].Name);
使用
vm.users = response.data;