mailman_73 mailman_73 - 3 months ago 5x
AngularJS Question

Avoid a repeated scope variable in different controllers in AngularJS

I've got few controllers working with different templates:

function($routeProvider) {
when('/', {
templateUrl: 'table_index.html',
controller: 'CurryListCtrl'
when('/cities/:cityId/', {
templateUrl: 'template-total.html',
controller: 'CurryDetailCtrl'
when('/cities/:cityId/mobile/', {
templateUrl: 'template-mobile.html',
controller: 'CurryMobileCtrl'
when('/cities/:cityId/online/', {
templateUrl: 'template-online.html',
controller: 'CurryOnlineCtrl'

All of theses controllers have $scope variable called

For example, the first one:

curryControllers.controller('CurryDesktopCtrl', ['$scope', '$routeParams', '$http', '$route',
function($scope, $routeParams, $http, $route) {
$scope.cityId = $routeParams.cityId;
$http.get('json/cities.json').success(function (data) {
$scope.cities = data;

The second one:

curryControllers.controller('CurryOnlineCtrl', ['$scope', '$routeParams', '$http', '$route',
function($scope, $routeParams, $http, $route) {
$scope.cityId = $routeParams.cityId;
$http.get('json/cities.json').success(function(data) {
$scope.cities = data;

Is it okay to have repeated $scope variables in different controllers?
How should I refactor the code in order to escape duplicates?


You can create a factory:

.factory('citiesFactory', function($http) {
   function getCities(){
      // return promise from function
      return $http.get("json/cities.json");

   return {
      getCities: getCities

then in your controller:

curryControllers.controller('CurryDesktopCtrl', ['$scope', '$routeParams', '$http', '$route', 'citiesFactory'
  function($scope, $routeParams, $http, $route, citiesFactory) {
    $scope.cityId = $routeParams.cityId;
       $scope.cities =;