Implement AngularJs within a custom namespace and remove window.angular

When developing my client's website, I utilized Angular JS 1.5.7. A unique dynamic mechanism was put in place to seamlessly integrate remote JS applications on the site. This process begins by loading a configuration file that specifies which additional scripts and stylesheets need to be loaded. However, one of the applications being loaded is using Angular JS version 1.3.9, causing an error due to version incompatibility with the ngAnimate module.

Initially, my solution involved moving window.angular to window.vendor.angular and deleting window.angular to ensure compatibility with the remote Angular JS version. Unfortunately, this approach led to complications as Angular JS relies on $window.angular at multiple points throughout the codebase.

In search of a better alternative, simply replacing window.angular and $window.angular is not feasible since I prefer to load AngularJS from a public CDN for performance reasons.

Currently, I am exploring ways to run Angular JS in complete isolation or implement something similar to jQuery.noConflict() from the jQuery library to resolve this issue seamlessly.

Answer №1

Finding a simple yet effective solution is key, even if it may not be the most glamorous. The trick here involves loading angularjs code and storing it in a designated place for later use. By loading angularjs version 1.5.7 and storing it separately as window.angular1_5_7, conflicts can be avoided when subsequent versions are loaded.

<script>
  // store angularjs internally
  window.angular1_5_7 = window.angular;
  window.angular = {};
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>

The application will then bootstrap normally with version 1.3.9. You can also utilize ng-app.

(function() {
  angular.module('app139', []);

  angular.element(document).ready(function() {
    var element = angular.element(document.getElementById('app139'));
    angular.bootstrap(element, ['app139']);
  });
})();

When bootstrapping your 1.5.7 app, specify using the stored angular version 1.5.7 (i.e., window.angular1_5_7).

(function(angular) {
  angular.module('app157', []);

  angular.element(document).ready(function() {
    var element = angular.element(document.getElementById('app157'));
    angular.bootstrap(element, ['app157']);
  });
})(window.angular1_5_7);

$window.angular and Proxy

If any conflicts arise due to $window.angular, consider utilizing ES6 proxies as a potential solution.

In this scenario, ES6 proxies intercept the get function for the property 'angular' within the $window service, ensuring that $window.angular remains secure. However, it's worth noting that full compatibility across all browsers may require further consideration until widespread adoption progresses.

angular.module('app157', [])
    .config(function($provide) {

      $provide.decorator('$window', function $windowDecorator($delegate) {

        return new Proxy($delegate, {
          get: function(target, prop) {
            return prop == 'angular' ?
              window.angular1_5_7 :
              target[prop]
          }
        });
      });
    })

A complete working example has been provided above for reference.

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

Replicating a Bootstrap element without transferring all event listeners

Recently, I posted a query on Stack Overflow regarding the cloning of a bootstrap element while excluding the copied event listener. The solution provided was to refrain from passing true to the clone() function. Upon further reflection, I've realize ...

Extract the color from the most prominent element in the viewport

I'm working on a button that will take the user to the bottom of the page, and I want the background color of the button to match the color of the first element that touches the viewport. The button is functioning properly, but I'm having trouble ...

Is it possible to collapse and expand individual rows within the Material-UI DataGrid component?

Is there a way to create expand-collapse functionality for each row in Material-UI DataGrid? While I understand that we can achieve this with TableRow and manual rendering (Collapsible table), I am wondering if it is possible within the DataGrid component ...

Verify if there are DOM elements located within a DIV container, execute the functions associated with those elements sequentially

I am in the process of creating a game using HTML, CSS, and JavaScript. My focus right now is on manipulating DOM elements without relying on the canvas tag. The goal is to develop a pseudo graphical programming language, similar to the environment provide ...

JavaScript date selector allowing the selection of multiple dates

As a beginner in JavaScript, I am struggling to create a datepicker input field that allows multiple selections. Despite researching for solutions, none seem to fit my specific case. Can anyone offer guidance on how to achieve this? Your help is greatly ap ...

Tips for looping through nested JSON data in Google Sheets

In my attempt to iterate through the nested "line_items" element in a JSON response triggered by a post event, I aim to populate a Google Sheets spreadsheet using Google Apps Script. My objective is to write the elements within each "line_item" into new ro ...

Common mistakes made while working with decorators in Visual Studio Code

Having trouble compiling TypeScript to JavaScript when using decorators. A persistent error message I encounter is: app.ts:11:7 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ' ...

Issue with generating random cells in a table using a loop

Within my HTML code, I have a table constructed using the table element. To achieve the goal of randomly selecting specific cells from this table, I implemented a JavaScript function that utilizes a for loop for iteration purposes. Despite setting the loop ...

Transform the text color of a table generated by a v-for loop

I have a Vue.js setup to exhibit a collection of JSON data which consists mainly of numbers. These numbers are displayed in a table format, with one minor issue - if the number happens to be negative, the text color of its cell needs to be red. <table& ...

The search for 'sth' cannot be done using the 'in' operator on an undefined value

Here is the code snippet I'm working on: . . keydown: function(ev) { clearTimeout( $(this).data('timer') ); if ( 'abort' in $(this).data('xhr') ) $(this).data('xhr').abort(); // encountering an ...

Using Angular Directive to Process Array of Objects

I am facing an issue with passing an array of objects from my angular controller to a directive. The array looks something like this: [{ label: 'label1', data: [{ type: TimelineChart.TYPE.POINT, at: new Date([2015 ...

Zoom in on a canvas-inserted image by clicking it, using a snippet of jQuery and HTML5

I'm currently working on a canvas image that allows zooming in and out after clicking the control button. The original size of the red ball is 128x128px. However, when zooming in too much, the image gets clipped by its own container. How can I resolv ...

Steps for displaying the search results in a pop-up box

I'm having trouble figuring out what to put in the '()' of my JavaScript popup function. Can anyone help me with this issue? Thank you! :) <script> // Example of JavaScript popup window function function customPopup(url) { popupWindow ...

Learning how to implement server side rendering in React JS through tutorials

After diving into the world of React js and mastering the basics, I successfully created web pages using this technology. I also honed my skills with node js and express. However, now I am faced with a new challenge: server side rendering. The tutorials av ...

Trouble with clicking buttons in Java and Selenium web scraping

Hey everyone, Currently, I'm working on a Java Selenium script that automates clicking and filling forms for me. I've written a line of code that's causing me some trouble. The intention is to click on a button, but it's not happening ...

Applying styles to an active router-link in Vuejs: A step-by-step guide

I have a sidebar that contains multiple sidebar items like the following: <side-bar> <template slot="links"> <sidebar-item :link="{name: 'Home', icon: 'ni ni-shop text-primary', path: '/dashboard'} ...

React hooks - Issue with updating state properties within sidebar display

When resizing the window, I have an event that will display either the desktop sidebar or the mobile sidebar. However, there are variables that are not immediately updated to show the sidebar correctly based on the window size. In a desktop window, this ca ...

What is the best way to convert a dynamic HTML table with input fields into an Excel spreadsheet?

I have developed a JavaScript function to convert an HTML table into an Excel sheet. However, I am facing an issue where some fields in the table are enclosed in input tags instead of td tags, causing them to not appear in the Excel sheet. function expo ...

Components undergo a style transformation with Material UI

I've noticed that every time I render the component, the styles keep changing. import React from 'react'; import FormControl from '@material-ui/core/FormControl'; import MenuItem from '@material-ui/core/MenuItem'; im ...

Leveraging React's UseEffect() to retrieve information from GraphQL

I am currently attempting to retrieve data from graphQL. I understand that by placing a function inside the react UseEffect(), I can trigger the function once the data is updated and structured. However, while working on a chatroom feature, I am facing an ...