0

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
GeeWhizBang
  • 699
  • 4
  • 27
  • Possible duplicate of [Minify angularjs script results in error](http://stackoverflow.com/questions/35684870/minify-angularjs-script-results-in-error) – Michelangelo Nov 10 '16 at 15:02
  • 1
    Possible duplicate of [Angular minification with directive controller?](http://stackoverflow.com/questions/27727017/angular-minification-with-directive-controller) – Basim Hennawi Nov 10 '16 at 15:03
  • 1
    Your directive is not minification safe: https://docs.angularjs.org/guide/di#implicit-annotation – Matthew Green Nov 10 '16 at 15:03

1 Answers1

5

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 });
            });
        });
    };
}]);
ngCoder
  • 2,095
  • 1
  • 13
  • 22
  • 1
    I just figured out the same thing and it worked. I didn't notice earlier that $parse was something that had to be referenced from angular and not minified. – GeeWhizBang Nov 10 '16 at 15:38