Reputation: 763
i want to do something like :
1. Set $scope.val = <Some dynamic data>
2. Click a link and be routed to a new template (with the same controller).
3. $scope.val should still be the same value as it was on the last page.
Is somehow persisting data for the scope the right way to go about this, or is there some other way? Can you even create a controller that has a persisted scope between routes, except for saving it in a database of course.
Upvotes: 2
Views: 1915
Reputation: 6270
You can share data between controllers but not with the simple $scope
.
You can use services for this task.
A controller gets recreated whenever you access a new route. But a service is a singleton in your app. So data which is stored in a service can be accessed from every new controller.
Your service can be very simple and just return an empty object:
app.factory('sharedData', function() {
return {
name: 'Daniel'
};
});
Then in your controller you can simple set this data object from the service to $scope
.
app.controller('MainController', function($scope, sharedData) {
$scope.data = sharedData;
});
Here is a working Plunker
Upvotes: 1
Reputation: 1035
You could attach data to the $rootScope, but you want to use a service.
A service provides a method to keep data across the lifetime of the angular app. It's a way to communicate data across the controllers in a consistent way.
Create a service like this:
var DynamicData = angular.module('myApp', [])
.service('GetDynamicData', function () {
$scope.data = [];
$http.get('yourApiUrl/data.json').then(function(res){
$scope.data = res.data;
});
});
Then you can use this service in other controllers, like this:
var myApp = angular.module('myApp', ['GetDynamicData']);
myApp.controller('DataController', function ($scope, GetDynamicData) {
//provide some business logic on $scope.data
}
});
You can get some dynamic data with a service (using and then inject that service in a controller where you want to use that data. Check out the provider docs.
Upvotes: 1