-
Notifications
You must be signed in to change notification settings - Fork 0
Angular Services
$scope
shares data between controllers and templates. It doesn't share data between controllers. To share data between controllers you use a service. If you're having issues with child scopes and parent scopes, maybe you should be using a service.
Angular has five types of services:
- Value returns a value.
- Factory is the most often used service. They make lots of the same thing, i.e., every time you call the service you get another copy, all the same.
- Service use the new keyword and create a singleton service, i.e., a unique instance of the service.
-
Providers do something with
.config
. - Constant
app.value("message", "Hello world!");
You inject the value as a dependency thus, and then call it:
app.controller("myController", ["$scope", "message", function ($scope, message) {
console.log(message);
}];
Listing the dependency twice is done in case you intend to minimize your code. If you don't intend to minimize your code, save time and complexity:
app.controller("myController", "function ($scope, message) {
console.log(message);
// Hello, world!
};
You also need to link the file in index.html
:
<script type="text/javascript" src="javascript/services/messageValue.js"></script>
A basic factory looks like this:
app.factory('bettyFactory', function() {
console.log("Betty factory running!");
bettyScope = 'betty';
return bettyScope;
});
This file could be called bettyFactory.js
. It needs to be linked and registered. Linking is in index.html
:
<script type="text/javascript" src="javascript/services/bettyFactory.js"></script>
Registering or dependency injection is in the controller that you want to data to pass through to:
app.controller('MyController', ['$scope', '$location', 'bettyFactory', function($scope, $location, bettyFactory) {
...
This won't work:
app.factory('bettyFactory', function($scope) {
console.log("Betty factory running!");
$scope.bettyScope = 'betty';
});
You can't inject $scope
into services. Think about it, the purpose of a service is to pass data between controllers, and each controller has its own $scope
. Services have to be outside of all the scopes. Instead you use return
to pass data out of a service.
How do you pass data into a service?