Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mrsweaters/62d46001149f1d052199b41cc6bf66f9 to your computer and use it in GitHub Desktop.
Save mrsweaters/62d46001149f1d052199b41cc6bf66f9 to your computer and use it in GitHub Desktop.
AngularJS service instead of $rootScope
'use strict'
/**
* A sample controller that stores data in the $rootScope
*/
angular.module('sample').controller('usingRootScopeController', ['$rootScope', '$scope', function ($rootScope, $scope) {
// Resets the list of items.
$scope.reset = function () {
$rootScope.someList = [];
}
//Adds a new item to the list.
$scope.add = function (elem) {
//We need to do lazy initialization to avoid accidentally resetting the list
if (!$rootScope.someList) {
$rootScope.someList = [];
}
$rootScope.someList.push(elem);
}
}]);
'use strict'
/**
* Same example as before, but using a service to store data instead of the $rootScope
*/
angular.module('sample')
.controller('usingServiceController', ['listService', '$scope', function (listService, $scope) {
//Same functionality as before, but since this is javscript we can directly assign functions instead
//of creating passthroughs.
$scope.reset = listService.reset;
$scope.add = listService.add;
}])
.factory('listService', function () {
//Using a local variable here and closures we keep list encapsulated.
// We can also perform initialization here since this code is only run once.
var list = [];
var service = {};
service.reset = function () {
list = [];
}
service.add = function (elem) {
list.push(elem);
}
return service;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment