Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the proper way to wrap a third-party library as an Angular.js service?

Tags:

angularjs

svg

I'm trying to wrap Snap.svg as a service of my application. The code below works, but is this the right way to go about it?

var svgService = angular.module("svgService", []);

svgService.factory("svgService", [
  function () {
    if (Snap) {
      return Snap;
    }
  }
]);
like image 643
Michael P. Avatar asked Aug 02 '14 16:08

Michael P.


People also ask

What is Anguar JS used for?

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. AngularJS's data binding and dependency injection eliminate much of the code you would otherwise have to write.

What are AngularJS bindings?

Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.


1 Answers

Your if check would throw an ReferenceError: Snap is not defined error anyway if the Snap doesn't exist.

You could replace the condition statement like this to be safe:

if (typeof Snap !== 'undefined') {

or if the Snap is in window, just reference it directly:

if (window.Snap) {

and even better, at least when it come to unit testing, using a built-in $window service as it allow you to mock it out.

svgService.factory("svgService", function ($window) {
  // the if check is unnecessary since an undefined
  // is returned anyway when the Snap doesn't exist.
  return $window.Snap; 
});

Hope this helps.

like image 159
runTarm Avatar answered Oct 12 '22 16:10

runTarm