0

When I try to minify the following code it breaks. What's wrong? What's the simplest way to fix this?

(function () {
    'use strict';
    angular.module('weatherapp.weatherlist')
    .controller('WeatherlistController2', function($scope, utcFactory) { 
        var vm = this; 
        vm.utc = utcFactory.myUTC(); 
     })

    .factory('utcFactory', function() {
        var myUTC = function() {
          var offset = -new Date().getTimezoneOffset();
          var utc = ((offset > 0 ? '+' : '') + offset / 60);
          return utc;
        }

        return {
          myUTC: myUTC
        }
    });
})();
Agent Zebra
  • 4,410
  • 6
  • 33
  • 66

1 Answers1

1

This is a common problem. Use the array syntax for your controller:

.controller('WeatherlistController2', [ '$scope', 'utcFactory', function($scope, utcFactory) {}])

See here as well: Angularjs minify best practice

Community
  • 1
  • 1
AJ Meyghani
  • 4,389
  • 1
  • 31
  • 35
  • Why does minification break this? – Agent Zebra Jul 12 '16 at 22:52
  • 1
    By the way @AgentZebra, there are tools that will do this for you automatically as part of your build step, if you have one. gulp-ng-annotate, for example. – matmo Jul 12 '16 at 22:53
  • 1
    Minification breaks this because if you don't use the syntax that is mentioned above, angular literally calls the .toString() method on your controller function to determine what dependencies are being injected into your controller (in this case, $scope and utcFactory). When you minify your code, $scope and utcFactory are going to be minimized into random variabled like a or b, so when angular parses your function as text, it won't be able to inject 'a' or 'b', and then your whole application won't work. See http://anandmanisankar.com/posts/angularjs-dependency-injection-demystified/ – matmo Jul 12 '16 at 22:55
  • Just to add: Minifiers usually have a name mangling option. If that option is on, function parameters are changed to random variables like `a` or `b` .... – AJ Meyghani Jul 12 '16 at 22:57
  • @AminMeyghani Thanks, I figured this one out, how do you turn the name mangler on and off? – Agent Zebra Jul 18 '16 at 20:58
  • @matmo what does a good production build step look like? What tools / steps would you use / include? – Agent Zebra Jul 18 '16 at 20:59
  • @AgentZebra I did a [quick write up](https://gist.github.com/Matmo10/ae272de2513749f327a90cb2e1c57b1b) of the way I do things personally...I'm not claiming its the best way but it works (there are lots of people with strong opinions in the frontend ecosystem). Feel free to ask any further questions you have. – matmo Jul 19 '16 at 06:19
  • @matmo Thank you so much this is really very helpful. – Agent Zebra Jul 19 '16 at 21:09