AngularJS新手。
我正在尝试通过$http
和$q
从JSON文件中获取数据,并将数据附加到视图中。
但我无法做到。仅创建了3个li
元素,而JSON数据有6个记录。
我想使用诺言做到这一点,但它不起作用。
此Plunker证明了这个问题。
HTML:
<div class="container" ng-controller="dataCont">
<input type="text" name="text-field" id="text-field"/>
<ul>
<li ng-repeat="msg in messages">
{{ msg.name }}
</li>
</ul>
</div>
App.js:
"use strict";
var App = angular.module('app', []);
App.controller('dataCont', function($scope, messageData) {
$scope.messages = messageData.getMessageData();
// console.log($scope.messages);
})
Services.js:
App.factory('messageData', function($http, $q) {
return {
getMessageData: function() {
var deferred = $q.defer();
$http({method: 'GET', url: 'data.json'})
.success(function(data, status, headers, config) {
deferred.resolve(data);
})
.error(function(data, status, headers, config) {
deferred.reject(status);
})
return deferred.promise;
}
}
});
提前致谢。
答案 0 :(得分:3)
您需要使用then()
...
messageData.getMessageData().then(function (data) {
$scope.messages = data;
}, function (errorStatus) {
$scope.errorStatus = errorStatus;
});
您还可以使用$ http ...
返回的承诺简化服务App.factory('messageData', function($http) {
return {
getMessageData: function() {
return $http({method: 'GET', url: 'data.json'})
.then(function(response) {
return response.data;
}, function(errorResponse) {
throw errorResponse.status;
});
}
}
});