3

I've noticed that it is not common to wrap third party scripts in a angular js provider for dependency injection and I am not sure why. I am new to angular and trying to figure out what the best way to leverage the DI with jquery plugins, lodash, modernizr, etc...

Consider this example I found:

var App = angular.module('Toolbar', []);

App.directive('toolbarTip', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            $(element).toolbar(scope.$eval(attrs.toolbarTip));
        }
    };
});

http://jsfiddle.net/codef0rmer/TH87t/

This seems to work totally fine, but would it be better to create a value, constant or other provider for the toolbar tip jQuery plugin than inject that into the directive? Also, should this directive require jQuery (not jQlite), should that be wrapped in a provider and injected as well?

Similarly with modernizr and lodash, would this be considered the best way to appraoch DI with those libraries?

With Modernizr:

angular.module('someApp', [])


.provider('Modernizr', function () {
    this.$get = function () {
        return Modernizr || {};
    };
})

.factory('cgEvents', function(Modernizr) {
    return {
        buttonPressedEvent : function() {
            if ( Modernizr.touch ) {
                return 'touchstart';
            } else {
                return 'click';
            }
        }
    };
})

With lodash:

angular.module('someApp', [])

.factory('_', function() {
    return window._; // assumes lodash has already been loaded on the page
});

.directive('cgFillViewPort', function (_) {
    return {
        restrict: 'A',
        link: function(scope, $elm) {

            var resizer = function() {
                //code fired on resize...
            };

            $(window).resize( _.throttle( resizer, 100 ));
        }
    };
})

Is this the a valid way of using dependency injection? Any insight on this would be greatly appreciated!

cartogram
  • 31
  • 2
  • Try to combine `requirejs` with `angularjs` to keep angular stuff and other libs stay separated – Umidbek Jan 04 '15 at 06:31

1 Answers1

0

I think you're on the right path. So far I've been doing the same and worked ok(but as my application gets bigger I will refactor my code to use requirejs. Keep in mind, though, that jquery can cause memory leaks in angular. Since AngularJS apps are single-page apps and jquery objects are outside the angular scope, they don't get destroyed even though the route gets changed! So be careful to delete your jquery references in directives when the $destroy event is fired.

More details on this issue here.

Community
  • 1
  • 1
Cristi Berceanu
  • 1,693
  • 1
  • 10
  • 12