GeeWhizBang GeeWhizBang - 22 days ago 18
AngularJS Question

AngularJS directive fails when minified

I'm using a minifier addon to visual studio that mostly works except for this one block of AngularJS code

This is the unminified code:

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

svgBuildInterface.directive('ngRightClick', function ($parse) {
return function (scope, element, attrs) {
var fn = $parse(attrs.ngRightClick);
element.bind('contextmenu', function (event) {
scope.$apply(function () {
event.preventDefault();
fn(scope, { $event: event });
});
});
};
});


This is the pretty-printed minified code that fails:

svgBuildInterface = angular.module("svgBuildInterface", []);
svgBuildInterface.directive("ngRightClick", function(n) {
return function(t, i, r) {
var u = n(r.ngRightClick);
i.bind("contextmenu", function(n) {
t.$apply(function() {
n.preventDefault();
u(t, {
$event: n
})
})
})
}
});


I can't put a break point into the minified code to find out what is happening, but angularJS throws an exception:

Error: [$injector:unpr] http://errors.angularjs.org/1.5.7/
$injector/unpr?p0=nProvider%20%3C-%20n%20%3C-%20ngRightClickDirective

Answer

Change your directive like below,there are certain best practices to be followed when writing a controller or directive or whatever component of Angular js when you want to minify your JS.

One of them is passing dependency injection via []

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

svgBuildInterface.directive('ngRightClick',['$parse', function ($parse) {
    return function (scope, element, attrs) {
        var fn = $parse(attrs.ngRightClick);
        element.bind('contextmenu', function (event) {
            scope.$apply(function () {
                event.preventDefault();
                fn(scope, { $event: event });
            });
        });
    };
}]);
Comments