我正试图在Angular中控制器之间共享数据。这是我与Angular的第一个项目。
到目前为止,看起来“服务”是我可以在两个或更多控制器之间共享数据的一种方式。数据需要“实时”。使用Angular的$ http服务从服务器检索数据。
我遇到的问题是,我不明白一旦从服务器取出数据后如何添加数据。我有一个函数应该将新数据推送到一个中央阵列(在服务中),这必须自动更新应用程序中的其他位置。我已经浓缩了我的代码,所以你可以看到我正在尝试做什么。我可能会走错方向,所以请随时告诉我应该如何做到这一点。非常感谢。
// Setup a factory for processing posts and their data
app.factory( "AllEvents", [ "$http", function AllEventsFactory ( $http ) {
// Hold all posts from the database
var allEvents = [];
// Retrieve posts and return a promise object
function getEvents () {
// Retrieve events from the database
return $http( {
method: "GET",
url: "foo",
} );
}
// Allow a new post to be pushed onto the allEvents array
function pushNewEvent ( newEvent ) {
allEvents.push( newEvent ); // This needs to update "globally"
}
return {
getEvents: getEvents, // Get the events for the first time. TODO, only send $http request once.
pushNewEvent: pushNewEvent // Allow new events to be pushed on this object
}
} ] );
app.controller( "ExistingEventsController", [ "$scope", "AllEvents", function ( $scope, AllEvents ) {
// Get all current events from the AllEvents service using the promise object
AllEvents.getEvents().then(
function successCallback ( data ) {
$scope.events = data.data; // NOTE: I need this to be updated when the AllEvents.allEvents property is updated from other controllers
},
function errorCallback ( data ) {
// Handle the error
console.log( "There was an error" );
}
);
} ] );
app.controller( "NewEventController", [ "$scope", "$http", "$timeout", "AllEvents", function( $scope, $http, $timeout, AllEvents ) {
$scope.addNewEvent = function ( newEventData ) {
// Sample data
var newEventData = {
post_title : "This is my example title"
};
AllEvents.pushNewEvent( newEventData ); // NOTE: How should this work..?
}
} ] );