Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eliminate minification errors when using $controller in AngularJS

angular.module('mainApp').
  controller('dynamicRouteController', ['$scope', '$controller', '$routeParams', function($scope, $controller, $routeParams) {
    if(/^\d+$/.test($routeParams.pageOrName)) {
      $scope.controller = $controller('thisController', { $scope: $scope }).constructor;
      $scope.templateUrl = '/www/thisPage';
    } else {
      $scope.controller = $controller('thatController', { $scope: $scope }).constructor;
      $scope.templateUrl = '/www/thatPage';
    }
  }]);

this minifies to:

"use strict";
angular.module("mainApp").
controller("dynamicRouteController",["$scope",‌​"$controller","$routeParams",function(a,b,c){
/^\d+$/.test(c.pageOrName)?
(a.contro‌​ller=b("thisController",{$scope:a}).constructor,a.templateUrl="/www/thisPage"):
(a‌​.controller=b("thatController",{$scope:a}).constructor,a.templateUrl="/www/thatPa‌​ge")
}])

This is having issues minifying, I think its because of the {$scope : $scope} being altered... First time I have run into this/used this method. Anyone know a better way to write this so it minifies correctly?

EDIT: so whats happening, is that it is passing the {$scope: a} which is fine, but on that referenced controller, when its minified, that $scope has become a or b or e depending... so if I write the code "pre-minified", meaning I literally find what letter represents $scope in the other controller, I can get it to work, but thats so hacky! Again, any ideas?

Using Grunt for minification Angular 1.0.5 ... maybe fixed in later versions?

2nd EDIT: A decent answer is to throw both controllers into the same file, explicitly... which is ugly... but it works! so with in one controller, I am declaring 2 sub controllers, which is lame. If you know of another way please share with the class!

like image 520
mclenithan Avatar asked Aug 08 '13 23:08

mclenithan


1 Answers

I was working on this issue with @mclenithan and what we came up with is:

$scope.controller = ['$scope', 'service1', 'service2', 
    $controller('thisController', { $scope: $scope }).constructor];

The main issue was the controllers thisController and thatController had more parameters to inject than just $scope (in this example it expects service1 and service2).

The $controller(...).constructor was returning the minified controller function with the parameters renamed to a, b, c, d, etc. When Angular was trying to instantiate the controller it had issues trying to find the correct services to inject.

Using the array notation instead of just the controller function fixed the issue. See a note on minification in the tutorial for more info.

Also see this question for context on what we were trying to do to begin with.

like image 83
Gloopy Avatar answered Nov 04 '22 12:11

Gloopy