Davide Pastore
Davide Pastore

Reputation: 8738

Set common scope variables in run

I'm developing a web application with AngularJS and I would like to know how I can set some $scope variables that are commons to all my controllers (or great part 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 everytime the same thing 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 services for this purpose, because I don't want the assignments in every controller.

Upvotes: 3

Views: 5016

Answers (1)

jValdron
jValdron

Reputation: 3418

To add to my comment:

This is what I would do, create a controller for my app, which would 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 seperate $scope, to access that scope from other "child" controllers, you'd do $scope.$parent.

However, if we take your original 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'd be able to use $rootScope in your controllers, or universe and etc in your HTML/views.

Upvotes: 4

Related Questions