mailman_73 mailman_73 - 5 months ago 13
AngularJS Question

Avoid a repeated scope variable in different controllers in AngularJS

I've got few controllers working with different templates:

curryApp.config(['$routeProvider',
function($routeProvider) {
$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
cities

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?

Answer

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;
    citiesFactory.getCities().then(function(response){
       $scope.cities = response.data;
    });
      ...