Is there unnecessary repetition of data in Angular and Requirejs?

When running Angular under Requirejs, I encountered a situation where the data in the controller class was being repeated twice. This issue only seemed to occur when ng-app="myApp" was present in the div. Why is this happening?

Here is an example from welcomeController.js:

define(['app'], function (app) {
    app.controller('welcomeController', ['$scope', function($scope) { 
        //your minsafe controller 
        $scope.message = "Message from WelcomeController"; 
        console.log($scope.message); // it is repeated twice here.
    }]);
});

In my HTML file:

<head>
    <link rel="stylesheet" href="style.css">
    <script data-main="scripts/main.js" src="scripts/vendors/requirejs/require.js"></script>
</head>

<body>
    <div ng-app="myApp">

        <div ng-controller="welcomeController">

            {{message}}

        </div>

    </div>
</body>

The main.js file contains:

require.config({
    paths: {
        'domReady': 'vendors/requirejs-domready/domReady',
        'angular': 'vendors/angular/angular',
        'angular-route': 'vendors/angular-route/angular-route',
        'jquery': 'vendors/jquery/dist/jquery'
    },

    shim: {
        'angular': {
            exports: 'angular'
        },
        'angular-route': {
            exports: 'angular'
        }
    }
});

define([
    'controllers/welcomeController',
    'bootstrap'
]);

And bootstrap.js has:

define([
    'require',
    'angular',
    'app'
], function (require, ng) {
    'use strict';

    require(['domReady!'], function (document) {
        ng.bootstrap(document, ['myApp']);
    });
});

In app.js,

define([
    'angular'
], function (ng) {
    'use strict';

    return ng.module('myApp', []);

});

It seems that everything works fine with Angular alone, without Requirejs. The duplication issue does not arise when ng-app="myApp" is included in the `div`. But under Requirejs with Angular, the problem occurs.

<head>
    <link rel="stylesheet" href="style.css">
    <script src="scripts/vendors/angular/angular.js"></script>
    <script>
        var myApp = angular.module('myApp',[]);

        myApp.controller('welcomeController', ['$scope', function($scope) {
            $scope.message = "Message from WelcomeController"; 
            console.log($scope.message); // It occurs only once.
        }]);
    </script>
</head>

<body>
    <div ng-app="myApp">

        <div ng-controller="welcomeController">

            {{message}}

        </div>

    </div>
</body>

What could be causing this discrepancy between working with Angular and Requirejs together versus using Angular alone?

Answer №1

You're initializing Angular twice: once using the ng-app directive and again with the ng.bootstrap(...) code in bootstrap.js! Choose either automatic (ng-app) or manual (angular.bootstrap) initialization.

Additionally, as Josep suggested in his (deleted) response, it's recommended to shim angular-route like this:

shim: {
    'angular-route': {
        deps: ['angular']
    }
}

This isn't the root cause of the issue, but it can help prevent potential future complications (such as routes being loaded before Angular).


For more insights on Angular-RequireJS integration with lazy loading, check out angular-require-lazy

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

Switching the event handler in jQuery from click to onload

I have implemented an onclick function that enables an object to go fullscreen when clicked. However, I would like the object to automatically be fullscreen when the page loads, without requiring any user interaction. fbNav.find('ul li.fullscreen&a ...

Allow entry fields and a submit button to become active once the form has been submitted on ASP.NET MVC 4

I want the update button to be activated after submitting the form. Take a look at my code: VIEW: @using (Html.BeginForm("ProcessTech", "Home", FormMethod.Post)) { @Html.TextBoxFor(m => m.techNo, new { @class = "form-control maintain-t ...

Organize data by month using angularjs

I'm working on an HTML page that displays a categorized list of data for each month. Here's a snippet of how the page looks: July, 2014: Monday 7th Data 7 Data 6 Friday 4th Data 5 Data 4 May, 2014: Sunday 15th Data 3 Thursday 8th Data ...

Webpage featuring tabs aligned horizontally

Can anyone guide me on setting up horizontal tabs similar to the design in this image: https://i.sstatic.net/ewXO4.png? Below is the code snippet: <label class="formlabel">Title 1:</label> <div id="radio_form"> <label><inpu ...

Obtaining a subset of data from firebase

I am currently working on retrieving a sub-collection from the Firestore database using Angular. In my database, I have a collection called 'Company' which contains fields for 'Name' and 'Id', as well as a sub-collection named ...

Exploring the Printing Options in Opera using ASP.NET

When using JavaScript, I encountered an issue where the print dialog box would not appear. The new window would open successfully, but the print dialog was missing. This problem only occurred in Opera, while IE, Chrome, and Mozilla worked fine. I have rese ...

Is it feasible to achieve a full 100% screen width within a confined div using relative positioning?

Can a div expand to 100vw within a parent div that is relative and has a limited width, without losing its height in the document like it would if positioned absolute? Is it achievable with pure CSS or do I need some jQuery or JS? body { background: ...

What is the best way to adjust the maximum width of Reddit's embedded comment iframe?

Reddit provides a code that can be embedded to display their comments on a website, As an example: <div class="reddit-embed" data-embed-media="www.redditmedia.com" data-embed-parent="false" data-embed-live="false" data-embed-uuid="24a3e666-f855-4664 ...

Error: The module could not be found due to an inability to resolve the parsed request

I am working on a project that uses class components as a requirement by the company, and I cannot switch to function components. After running elint --fix and restarting the project, I encountered an error that is specific to just one file. The error me ...

Use $location.search to clean up after each use

Our team is fairly new to working with AngularJS, and we have encountered a situation in our project where we need to navigate from one webpage to another while passing parameters. We achieve this by using the code snippet below: $location.path("/newpage" ...

Steps to turn off a Material UI CSS class for an element universally

Utilizing the Material UI Typography element with the css class MuiTypography-h1, I am seeking to globally disable its usage throughout the entire codebase. <Typography variant="h1" sx={{ width: '100px', height: '55px ...

Creating a JavaScript object using a provided JSON string

Having a large JSON data that needs to be parsed in order to extract objects from the given JSON string. The top part of the data has been included here. Initial attempts to parse it using the code snippet below resulted in an error: let obj = JSON.parse(t ...

I am looking to insert a jQuery value or variable into the plugin options

How can I insert a jQuery value or variable into plugin options? This is my current script: $(document).ready(function() { // var bannerheight = 580; if ($(window).width() < 2100) { var bannerheight = 410; var opts = JSON.parse( ...

The object holds a value

How can I successfully put an object into a value attribute, for example: <option value={valueSort}>// valueSort = {name: 'ASC'}, to sort by name in my project? Currently, the result shows as [object Object] and I'm unsure of what that ...

Vue.js - computed property not rendering in repeated list

It seems like the issue lies in the timing rather than being related to asynchronous operations. I'm currently iterating through an object and displaying a list of items. One of the values requires calculation using a method. While the direct values ...

Selenium's click() method in Python seems to experience issues when used within a script, but functions properly when used through

While working with python 3 selenium, I encountered an issue when trying to login to the Zomato website. When running a script, the login button was clicked but the dialog box did not open. However, when executing the same statements in the command line or ...

Issue with Vue.js Typescript when setting a debounced function

Upon debouncing a function in my Vue.js application, I encountered the following error message: Type 'DebouncedFunc<(queryParams: QueryParams, page?: number) => Promise<void>>' is not assignable to type '(queryParams: QueryPa ...

The art of bringing a pseudo class to life through animation

Seeking assistance with achieving a unique effect on click event. I have set up a slanted or razor-blade style div using a parent div element and a pseudo-element :after (as shown below). My goal is to change the skew angle when the user clicks on the pare ...

I seem to be having trouble encoding a character in Internet Explorer 8, do you have any suggestions on how to fix

After making an XHR get request to my server side, I encountered a problem with Chinese characters in the request URL. While non-IE browsers worked fine, IE8 did not automatically encode the characters, leading to data handling issues on the server side. H ...

Is there a way to transfer an image from background.js to background.html?

I'm in the process of creating a chrome extension that involves making an API call every hour to retrieve an image, which I then want to save in chrome.storage.local. However, the size of the image is quite large, so I'm resizing it using a canv ...