我在Angular遇到问题,我有一个控制器从服务中获取数据。控制器从服务获取数据,但它只返回最后一个元素。
请参阅此jsfiddle以获取示例:http://jsfiddle.net/c1104q9b/
HTML:
<div ng-app="myApp">
<div ng-controller="MessageController">
<ul>
<li ng-repeat="message in messageData">{{message.title}} - {{message.message}}</li>
</ul>
</div>
</div>
JAVASCRIPT:
var app = angular.module('myApp', []);
app.service('messageService', function () {
// private data
var data= [
{ id: 1, title: 1, message: 'some new message1',
id: 2, title: 2, message: 'some new message2',
id: 3, title: 3, message: 'some new message3',
id: 4, title: 4, message: 'some new message4',
id: 5, title: 5, message: 'some new message5',
id: 6, title: 6, message: 'some new message6',
id: 7, title: 7, message: 'some new message7',
id: 8, title: 8, message: 'some new message8'
}
];
return {
getMessages: function () {
// Expose private data
return data;
},
addMessage: function (title, message) {
// Public function that modifies private data
var currentIndex = data.length + 1;
data.push({ id:currentIndex, title: title, message: 'added a new message ' + message })
},
deleteMessage: function (id) {
// Public function that modifies private data
var oldMessages = data;
data = [];
angular.forEach(oldMessages, function(message){
if (message.id !== id) data.push(message);
});
}
};
});
app.controller('MessageController', ['$scope', 'messageService', function($scope, messageService) {
$scope.messageData = messageService.getMessages();
//messageService.addMessage('some title', 'some new message');
$scope.addMessage = function (title, message) {
if (title != ''){
messageService.addMessage(title, message);
};
};
$scope.deleteMessage = function (id) {
//
};
}]);
答案 0 :(得分:2)
你的json无效。每个条目都需要包含在自己的{}。
中请参阅http://jsfiddle.net/rbqyf78e/
var data= [
{ id: 1, title: 1, message: 'some new message1' },
{ id: 2, title: 2, message: 'some new message2' },
{ id: 3, title: 3, message: 'some new message3' },
{ id: 4, title: 4, message: 'some new message4' },
{ id: 5, title: 5, message: 'some new message5' },
{ id: 6, title: 6, message: 'some new message6' },
{ id: 7, title: 7, message: 'some new message7' },
{ id: 8, title: 8, message: 'some new message8' }
];
答案 1 :(得分:2)
这是因为您的数据是具有单个对象的数组。结构需要如下:
var data= [
{ id: 1, title: 1, message: 'some new message1'},
{id: 2, title: 2, message: 'some new message2'},
{ id: 3, title: 3, message: 'some new message3'},
{id: 4, title: 4, message: 'some new message4'},
{id: 5, title: 5, message: 'some new message5'},
{id: 6, title: 6, message: 'some new message6'},
{id: 7, title: 7, message: 'some new message7'},
{id: 8, title: 8, message: 'some new message8'
}
];