I just setup routes in my angular app. The first view, List makes an http call to get a list of presentations
function ListController($scope, $http)
{
$scope.error = null;
$scope.presentations = null;
$scope.requesting = true;
$scope.currentTitle = '-1';
$data = {
'type' : 'presentations'
};
$http.post('resources/request.php', $data, {timeout:20000})
.success(function(data, status, headers, config)
{
$scope.requesting = false;
$scope.presentations = data;
})
.error(function(data, status, headers, config)
{
$scope.requesting = false;
log(status + ', data:" ' + data + '"');
}
}
);
}
My route is
angular.module('main',[]).
config(function($routeProvider) {
$routeProvider.
when('/', {controller:ListController, templateUrl:'resources/views/list.html'}).
when('/view/:id', {controller:VforumController, templateUrl:'resources/views/vforum.html'}).
otherwise({redirectTo:'/'});
});
the problem I have is when I go to #/view/:id and then back to / the $http call gets called again. How can I make it so it only loads the first time going into the app and reference the same data that was loaded the first time?
I attempted to create a variable outside of angular and set it equal to the data loaded the first time. Then, in the ListController basically did a if data is null, do the $http call else set $scope.data = data but that didn't work. The list view was just blank. $scope.data is what builds my list.
What you want is a service, which in angular is a singleton:
.factory( 'myDataService', function ( $http ) {
var promise;
return function ( $data ) {
if ( ! angular.isDefined( promise ) ) {
promise = $http.post('resources/request.php', $data, {timeout:20000});
}
return promise;
}
});
And now you can simply replace the call to $http with a call to your service:
function ListController( $scope, myDataService )
{
// ...
myDataService( $data ).then( function success( response ) {
$scope.requesting = false;
$scope.presentations = response.data;
}, function error( response ) {
$scope.requesting = false;
log(status + ', data:" ' + response.data + '"');
});
}