I found a javascript library "https://github.com/jvail/spatiasql.js" that I want to use with angular. I know I could just include it in the name of my scripts in my header, but I want to be able to inject it into my angular modules to access it from the controllers. I believe to do this I will need to have a custom built angular directive from this javascript library, correct? If so how do I accomplish this?
3 Answers
The simplest way would be to create a factory that returns the library's namespace object, e.g.
(function() {
angular
.module("myModule")
.factory("sql", SqlFactory);
SqlFactory.$inject = ['$window'];
function SqlFactory($window) {
return $window.spatiasql;
}
})();
Then you can inject it:
(function() {
angular
.module("myModule")
.service("someService", SomeService);
SomeService.$inject = ["sql"];
function SomeService(sql) {
var db = new sql.DataBase();
}
})();
7 Comments
new sql.Database() is because Angular's DI assigns the injected members to the function arguments positionally. This means you can rename the argument from $SQL to sql (in the function signature, not in the dependency array) and it'll work just fine.No need to inject it in order to access functions from it in your controllers. You can just call it's methods from you controllers.
2 Comments
Injecting is not an angular construct. It is an implementation of the inversion of control design pattern. It is one of the foundations of modern object oriented design. The purpose of it is to make unit tests possible. It leads to code that isn't tightly coupled. DI allows you to code to an interface rather than an implementation.