I am currently writing a frontend app with angular js.
I am using Restangular to handle all the REST request. Loading data currently works perfect.
I want to do the following:
I want to write a service/factory/provider, that returns the name of every language. This call only needs to done once in the whole workflow (it is unlikely that the languages while a user is using the application).
So I tried something like this:
'use strict';
angular.module('maroziFrontendApp')
.service('LanguagesService', function(Restangular) {
this.languages = Restangular.one('languages').get();
});
But when I inject this in my controller (or Restangular element transformer), I will only get the promise. I then have to do another callback and that messes up the workflow.
I also tried:
'use strict';
angular.module('maroziFrontendApp')
.service('LanguagesService', function(Restangular) {
Restangular.one('languages').get().then(function(languages) {
this.languages = languages;
});
});
But this returns undefined
when injected.
To clarify:
I want the languages to be loaded before the controller (or elementtransformer) is hit. I cannot use resolve
because I am not only using this service in a controller.
Is there an easy way?
You can also use $object
now in Restangular since version 1.2.0
So your code would be:
angular.module('maroziFrontendApp')
.service('LanguagesService', function(Restangular) {
this.languages = Restangular.one('languages').get().$object;
});
Then in your controller:
$scope.languages = LanguageService.languages
And in the HTML:
<span>{{languages.name}}</span>
This looks much better :)