Created
May 27, 2015 12:44
-
-
Save pablotdl/2a5e22012d927951e309 to your computer and use it in GitHub Desktop.
AngularJS service instead of $rootScope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
} | |
}]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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