Set common scope variables in perspective
I am developing a web application with AngularJS and I would like to know how I can set some variables $scope
that are shared by all my controllers (or most of them).
What I am trying:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ui.bootstrap'])
.run(function($ionicPlatform, $rootScope, $location, Common) {
$ionicPlatform.ready(function() {
//Set default global values
$rootScope.$on('$stateChangeSuccess', function (event) {
$scope.universe = "Universe and other things :)";
$scope.elsewhere = "Good day sir";
$scope.fish = "Perfectly well";
});
});
});
});
So I don't have to write the same thing every time in every controller:
angular.module('starter.controllers').controller('Controller1', function($scope) {
//I don't want this:
$scope.universe = "Universe and other things :)";
});
angular.module('starter.controllers').controller('Controller2', function($scope) {
//I don't want this:
$scope.elsewhere = "Good day sir";
});
angular.module('starter.controllers').controller('Controller3', function($scope) {
//I don't want this:
$scope.fish = "Perfectly well";
});
The important thing is that I don't even want to use it services
for this purpose, because I don't need assignments in every controller.
source to share
Add to my comment:
This is what I would like to do, create a controller for my application to be my "global" stuff.
.controller('AppCtrl', ['$scope', function AppCtrl($scope) {
$scope.$on('$stateChangeSuccess', function () {
$scope.universe = "Universe and other things :)";
$scope.elsewhere = "Good day sir";
$scope.fish = "Perfectly well";
});
});
And add this to your HTML:
<html ng-app="myAppName" ng-controller="AppCtrl">
So, this will create a separate $scope
one to access this area from other "child" controllers, you would $scope.$parent
.
However, if you take the source code, this should work:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ui.bootstrap'])
.run(function($ionicPlatform, $rootScope, $location, Common) {
$ionicPlatform.ready(function() {
//Set default global values
$rootScope.$on('$stateChangeSuccess', function (event) {
$rootScope.universe = "Universe and other things :)";
$rootScope.elsewhere = "Good day sir";
$rootScope.fish = "Perfectly well";
});
});
});
});
And then you can use $rootScope
in your controllers or universe
etc. in their HTML / views.
source to share