Reputation: 11162
// Somewhere in FooCtrl
$scope.myvar = 'titi'
$location.path('/viewSubscribe'); // redirection to the subscribe page
I'd like to be able to retrieve the "myvar" variable in the $scope of SubscribeCtrl (linked to /viewSubscribe route).
What is the clean way to do it? Thanks.
Upvotes: 0
Views: 195
Reputation: 16263
Well, there are several ways, depending on the use case. Here are some approaches ordered by level of relevancy to yours:
Pass it as a path variable, and define the variable name in when routing (in the $routeProvider
configuration):
// somewhere
$scope.myvar = 'titi';
$location.path('/viewSubscribe/' + $scope.myvar);
// ...
// in the module configuration
app.config(function ($routeProvider) {
$routeProvider
.when('/viewSubscribe/:myVar', {
templateUrl: 'views/myView.html',
controller: 'MyCtrl'
})
// etc.
});
Then you can inject the route parameters service to the desired location, and get the path variable's value:
// somewhere else
app.controller('MyCtrl', function($routeParams, $log) {
$log.info($routeParams['myVar']); // --> 'titi'
});
You can fire events to scopes up or down the hierarchy with the scope's $emit()
or $broadcast()
, respectively, e.g.:
app.controller('ParentCtrl', function($scope) {
$scope.$watch('model.text', function(newVal) {
$scope.$broadcast('myVarChanged', newVal);
});
});
app.controller('ChildCtrl', function($scope, $log) {
$scope.$on('myVarChanged', function (myVar) {
$log.info(myVar); // --> 'titi'
});
});
You can also set it once, and get it everywhere, if you declare it as a constant (or a value):
// at some outer level
app.constant('myVar', 'titi');
// anywhere, really
app.controller('MyCtrl', function(myVar, $log) {
$log.info(myVar); // --> 'titi'
});
Declare it in the root scope, so it is shared to all scopes:
app.run(function ($rootScope) {
$rootScope.myVar = 'titi';
});
// later
app.controller('MyCtrl', function($rootScope, $log) {
$log.info($rootScope.myVar); // --> 'titi'
$log.info($scope.myVar); // --> 'titi'
});
This method is less recommended, as it sets a common property for all inherited scopes, which can be easily overridden or shadowed (scopes are inherited prototypaly) and it cannot be used with isolated scopes (i.e. in directives that define their scope as such).
Upvotes: 3
Reputation: 46
In the case you don't want to retrieve the variable as a path parameter you can also make use of services. These are guaranteed to last for the duration of an AngularJS app. See http://docs.angularjs.org/guide/services
You can then store the variables inside your service as you would from a normal Java-like class and pass the services via dependency injection.
Upvotes: 0