We have previously discussed that a controller might not be a good place to hold on to data. If the controller goes out of the scope, the data residing in the controller will become inaccessible, and garbage will get collected in the JavaScript virtual machine.
Services are singletons, on the other hand. They get instantiated once and stay alive during the entire life cycle of the application. Let's create such a service.
We will make this service known to the application by editing app.js
as follows:
'use strict'; angular.module('myApp', ['myApp.controllers', 'myApp.filters', 'myApp.services', 'ng-grid']);
Then, we create a file named services.js
that contains the following code:
'use strict'; /** data service, manages data model throughout the life cycle of the application */ angular.module('myApp.services', []).factory('dataService', function () { var exports = {}; exports.data = ["x", "y"]; return exports; });
In this service module, we use the...