I'm investigating the possibility of using AngularJS as a framework for defining web components declaratively (avoiding the need for controllers as much as possible). The majority of the functionality required can already be achieved with Angular's inbuilt directives, however I would also like to be able to iterate over the results of various services used to request data asynchronously.
The functionality I need could be easily achieved by injecting the service into a controller and storing the result on the scope, but I was hoping there would be a method for achieving this without needing a controller at all (specifically, I'm hoping to generate templates rather than hand write them).
Is there any built in way to achieve this in Angular (e.g. a way to include a service call to a repeat expression)? If not, what would be the most effective way of accomplishing this? I would assume that I should be able to create a new directive that takes a reference to a service, but I'm not sure if this is the correct way to achieve this.
To make a general purpose directive, where a service can be declared in the HTML rather than be injected as part of the directive definition, the $injector can be used:
<some_element ... my-directive service="myService">
Directive:
myApp.directive('myDirective', function($injector) {
return {
link: function(scope, element, attrs) {
var service = $injector.get(attrs.service);
service.someMethod();
...
}
}
});
Note: I haven't yet tested the above technique to see if will actually work, but I've tried the technique with controllers and it works.
For this technique to be useful, you'd obviously have to come up with a static service API, and only services that use that API could be used.