Singleton controller in AngularJs

I have a directive: in the template:

<territorial-selector></territorial-selector> 

in js:

 app.directive('territorialSelector', function() { return { restrict: 'E' ,templateUrl: 'partials/territorial-selector.html' ,controller: 'TerritorialSelectorController' }; }; 

As you can see, using the "TerritorialSelectorController" directive

Elsewhere, I have a button that should execute the loadTerritories () method from the TerritorialSelectorController. I created this button:

 <button ng-controller="TerritorialSelectorController" ng-click="loadTerritories()">BUTTON</button> 

The problem is that in this case the TerritorialSelectorController creates two times. Here is the TerritorialSelectorController code:

 app.controller('TerritorialSelectorController', ['$scope', function($scope) { alert('AAAAA'); // I have alert two times }]); 

And I need only one controller object.

+5
source share
1 answer

If you want the functionality to work as a singleton, you need it to be inside the service accessible by your controllers. Controllers are not single; you can have many, many instances of the same base controller in your code.

If you instead create a service, then the general data / functionality that each controller must have can be hosted and accessed through this service.

Here's a Plunk demo showing two controllers sharing data through a service. These are not two controllers of the same type, but they will show you how the services work.

Here is the code from the demo. Controller:

 app.controller('SunListCtrl', function($scope, List, $log) { $scope.items = List.getList(); $scope.$on('updatedList', function() { $scope.items = List.getList(); $log.info('List has been updated. Size = ' + $scope.items.length); $log.info('\tNow set to: ' + $scope.items); }); }); 

Services:

 app.service('List', function($rootScope, $log) { service = {}; // the service object we'll return var dateValue = 'date'; var geoValue = 'geo'; var theList = []; service.setGeo = function(data) { geoValue = data; updateList(); } service.setDate = function(data) { dateValue = data; updateList(); } function updateList() { theList = [dateValue, geoValue]; $rootScope.$broadcast('updatedList'); // broadcasts the update to listeners } service.getList = function() { return theList; } return service; }); 
+9
source

All Articles