What is causing the AngularJS script to malfunction when Closure Compiler is used?

I am currently experimenting with AngularJs and Play Framework 2.0 (Scala). Play utilizes Closure to reduce the size of Javascript files.

The code in my file looks like this:

// Defining a Module 'todoList' for Angular that will load the views. The views in this example are very basic, just to demonstrate the concept
angular.module('todoList', ['taskDoneFilter', 'todoServices']).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/all', {templateUrl: 'assets/angular/all.html',   controller: TodoCtrl}).
            when('/task/:id', {templateUrl: 'assets/angular/task.html', controller: TaskDetailCtrl}).
            otherwise({redirectTo: '/all'});
    }]);


// This filter allows us to convert strings. It adds an extra tick next to a task to indicate whether it's done or not
angular.module('taskDoneFilter', []).filter('checkmark', function() {
    return function(input) {
        return input ? '\u2713' : '\u2718';
    };
});


// When running tests with Jasmine, the jsRoutes object is not defined. This means we need to use a default route for the http call below
var tasksUrl = '/tasks/all';
if(!(typeof jsRoutes === "undefined")) {
  tasksUrl = jsRoutes.controllers.Application.tasks().url ;
}

// Definition of a Service that stores all the REST requests independently from the controllers to facilitate changes
angular.module('todoServices', ['ngResource']).
    factory('All', function ($resource) {
        return $resource(tasksUrl, {}, {
            query: {method: 'GET', params: {}, isArray: true}
        });
    })
    .factory('Task', function ($resource) {
        return $resource('tasks', {}, {
            add: {method: 'POST'}
        });
    });

/**
 * Controller behind the view, referenced by ng-controller
 * All methods and data models in the view correspond to this controller
 * @param $scope - model data injected into the controller
 */
var TodoCtrl = ['$scope', 'All', 'Task', function($scope, All, Task) {
    // Use the service to get the data
    $scope.todos = All.query();

    // Function called when submitting the form. Adds the task to the data model
    $scope.addTodo = function() {
        var txt = $scope.todoText;
        $scope.todos.push({text: txt, done: false});
        Task.save({msg: txt});
        $scope.todoText = '';
    };

    // Calculates the remaining todos
    $scope.remaining = function() {
        var count = 0;
        angular.forEach($scope.todos, function(todo) {
            count += todo.done ? 0 : 1;
        });
        return count;
    };

    // Archives completed tasks
    $scope.archive = function() {
        var oldTodos = $scope.todos;
        $scope.todos = [];
        angular.forEach(oldTodos, function(todo) {
            if (!todo.done) $scope.todos.push(todo);
        });
    };
}];

// Task details controller for providing a second view
var TaskDetailCtrl = ['$scope', '$routeParams', function($scope, $routeParams) {
    $scope.id = $routeParams.id;
}];

However, after minimizing the code, it stops working. Specifically, the following parts cause issues:

var module$todo={};

and

var TodoCtrl$$module$todo=

This results in the application breaking down.

If you have any insights on why this might be happening, I would greatly appreciate your input.

Answer №1

Your All & Task services are not optimized for minification. To ensure 'minify safe' functionality, it is recommended to use the array notation.

angular.module('todoServices', ['ngResource']).
    factory('All', ['$resource', function ($resource) {
        return $resource(tasksUrl, {}, {
            //The data model is loaded via a GET request to the app
            query: {method: 'GET', params: {}, isArray: true}
        });
    }])
    .factory('Task', ['$resource', function ($resource) {
        return $resource('tasks', {}, {
            add: {method: 'POST'}
        });
    }]);

Additionally, make sure to define your controller using angular.module(...).controller():

angular.module(...).controller('TodoCtrl', ['$scope', 'All', 'Task', function($scope, All, Task) {
}]);

Answer №2

For applications of a bigger scale, identifying areas where named references are not being used can be achieved by enabling strictDi (through the option to bootstrap call or adding the ng-strict-di attribute within the tag containing the ng-app attribute).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Constantly getting a false result when using Bcrypt.compareSync

Hey there, I'm currently working on setting up my first login functionality using sequelize, but I'm running into some issues with hashing and comparing hashes as it always returns false. Since I am still learning, I believe I may be making a mis ...

Error: The function stripHtml cannot be found

Currently, I am developing a blog website using Next Js. I encountered an issue while creating a rich text-editor API for the blog. When attempting to utilize string-strip-html, an error message was displayed as follows: C:\Users\alami\OneDr ...

JavaScript and jQuery validation issues persisting

Here is the HTML code I am using: <script src="js/validate.js"></script> <label>FIRST NAME:</label> <td> <input type="text" class="firstname" id="firstname" onKeyUp="firstname()" /> </td> <td> <label id=" ...

Extract metadata from a webpage using JavaScript regular expressions

Looking to extract meta tags data using JavaScript (jQuery) and regex. Below are some examples of meta tags: <meta name="description" content="Amazon.com : Google Chromecast HDMI Streaming Media Player : Streaming Media Clients : Electronics" /> &l ...

Creating a login system in Node.js with the help of Express

I'm currently working on building a login feature for a website using node.js with the express framework. The code seems to be running in an unexpected order and I'm having trouble figuring out how to resolve it. Below is a simplified version of ...

JS method for gradually reducing the opacity of various div elements

I currently have two divs with background images styled using CSS. My goal is to create a loop that fades them in and out continuously. While attempting to achieve this effect, I encountered some issues and the following code snippet doesn't seem to ...

Having trouble with the isAuthenticated() function in node.js when using passport?

In the process of developing an online course application, I am encountering an issue where only authenticated users should have access to view course details and lectures. To handle user authentication, I have implemented the local strategy using passport ...

Switch back and forth between `display: none` and `display: flex` using JavaScript

There is a JavaScript function in place for a responsive navigation system that includes a burger button to toggle the visibility of the navigation menu when the screen size is too small. The issue I am facing is that despite setting the CSS style as disp ...

Using Django with Ajax without the need for the JQuery library

Exploring the world of Ajax without jQuery Library has been quite a journey. I recently created a basic view that displays a random number on the screen. After adding a button and invoking the ajax function, I encountered an issue where clicking the button ...

Deactivating choices in Autoselect from Material UI

I am attempting to implement a feature in the autocomplete of material ui where options are disabled based on a specific condition. Each table row contains an autocomplete field, and when an option is selected in one row, it should be disabled in the next ...

How to configure Jest and React Testing Library with NextJS in TypeScript – troubleshooting issue with setting up jest.config.js

I am currently setting up Jest with a NextJS application, and in my jest.config.js file I have configured it as follows: module.exports = { testPathIgnorePatterns: ["<rootDir>/.next/", "node_modules/"], setupFilesAfterEnv: ...

Exploring the Interplay of Classic ASP and AJAX Variables References

When the page loads, I check for an empty session variable. If it is empty, I trigger an AJAX function to include a hidden login form with ASP script that becomes visible through JavaScript. This part of the process works smoothly. Upon submitting the for ...

Page Refresh Causes Angular Count to Reset to Zero

I'm facing an issue in my code where the counts for total and package get reset to 0 when the page is refreshed, even though labels have been scanned and added to the list. Below is a snippet of my code. Any suggestions on how to resolve this problem? ...

HTML / VUE - Enable users to simultaneously choose/activate numerous <input> elements and input text into them concurrently

I'm working with an HTML table that has 2 columns structured as follows: Item Amount Icecream $3 Hotdog $5 Hamburger $10 In the "amount" column, there are <input> elements within <td> tags. The functionality I am looking to ...

How come my event handler functions stop working when I update the HTML content? (jQuery)

Trying my hand at recreating the "Todo List" tutorial example from AngularJS with just jQuery/native JS for the sake of learning. While I understand that AngularJS is a more effective choice for this type of app, I'm using this as an educational exerc ...

Is it possible to remove a particular div after clicking the delete button, especially if multiple divs are displayed upon clicking the add

var count = 2; var countMax = 5; function adddt() { if (count > countMax) return; document.getElementById('dt-' + count + '').style.display = 'block'; count++; } <link href="https://maxcdn.bootstrapcdn.com/bo ...

Alert: React-Weather is causing an invalid element type in React

I am feeling overwhelmed. I have created a custom component called react-weather which has been installed using npm. Here is the code snippet for my self-written Weather.js component located in the src/components folder: import React, { Component } from & ...

Navigating through an array in jquery that has been populated by a php script

I am trying to access an array in jQuery that is returned by a PHP script through an Ajax call This is the Ajax call I am making to get the result from the PHP script: $.ajax({ url: "http://localhost/WCPM/index.php/demand/check_demand_ ...

"Encountering difficulties in displaying a local image through the use of require and

I've been struggling to display local images in my react app. I've tried calling the image within the render method using the require() function, like this: <img src={require('../../assets/svg/ic_planning.svg')} /> Even importin ...

What is the reasoning behind the consistent addition or subtraction of 7 from the initial data value upon mounting?

When the addsevendays and minussevendays methods are attached to buttons, they should add or subtract seven days from the date each time they are clicked. However, currently it only performs this action once in either direction. For example, if the date is ...