Dynamically loading Javascript snippets based on model changes in AngularJS

I am looking to dynamically load and unload JavaScript snippets when a model changes using ngSanitize.

Check out this demonstration of what I am attempting to achieve: http://jsbin.com/wenoz/5/edit?html,output

The concept is as follows:

* Save various JavaScript snippets in a database or string variables
* Dynamically load the JavaScript into the DOM when an Angular model is altered
* Remove any existing snippet from the DOM and initialize the new snippet

Any ideas or suggestions? Thank you!

Answer №1

It is not possible to completely eliminate the impact of JavaScript once it has been executed as it becomes integrated into the environment. One workaround is to use an iframe to create a separate isolated environment that doesn't have direct access to your main page. Alternatively, if you simply want to run scripts consecutively, you can store them in an array and utilize ng-repeat to dynamically create new script tags each time (JSBIN):

<h3>A Demo to Dynamically Add/Remove Javascript with AngularJS</h3>
<button ng-click="setScript(one)">One</button>
<button ng-click="setScript(two)">Two</button>
<button ng-click="setScript(three)">Three</button>


<script ng-repeat="script in scripts" ng-bind-html="script"></script>


<script>
  var app = angular.module('app', ['ngSanitize']);
  app.controller('mainController', function($scope){
    $scope.scripts = [];
    $scope.one = "alert('one')";
    $scope.two = "alert('two')";
    $scope.three = "alert('three')";
    $scope.script = '';
    $scope.setScript = function(script) {
      $scope.scripts = [script];
    }
  });
</script>

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

Steps for loading a directive into a module after instantiation with requirejs

Let me share a bit about my current challenge. Initially, I had all the necessary directive files injected into my main module in app.js using requirejs paths, and everything was functioning smoothly. It looked something like this: define(['angularAM ...

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

Tips for resolving the React Hook Type Error issue

Error Image const isLoggedIn = true; const handleChangeEvent = () => {}; const [displayPassword, setDisplayPassword] = useState(false); const handleTogglePassword = () => setDisplayPassword((prevDisplayPassword) => !prevDi ...

JavaScript method not properly sorting the last nested array

I am having trouble with sorting the last nested array using arr[i].sort(). Despite trying various methods such as FOR and WHILE loops along with different operators, I still cannot achieve the desired result. Can someone help me identify what I am doing w ...

Switching the image hosted on a local server when an option is selected from the dropdown menu

I am trying to create a functionality in my project where I have a select box and based on the option selected, I want to change the image displayed on the browser. However, I don't want to manually code all the images into my HTML file. Here is an ex ...

How to display the compilation date in npm

During npm run watch is running in the background, I can see a recompilation process every time I make a change to the jsx code. Is there a way for npm to display the last time a jsx file was compiled? Thank you ...

Add the word "String" in front of the moment timestamp

In my project, I have used React along with Material UI to show the message Running check... when the clicked state is set to true. If it's not true, then I am displaying a timestamp by utilizing the react-moment library. <Typography gutterBottom ...

What could be causing the JavaScript error in this code snippet?

Check out this code snippet: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My Cool App</title> </head> <body> <p id='nameDisplay'> Name Display Area </p> ...

An empty array should be returned if a blank string is provided as input

While I've tackled similar exercises in the past and always managed to solve them, this time I'm facing a roadblock with something quite simple. I'm working on creating a function that retrieves the middle characters from each word in a stri ...

Encountering a Bootstrap <div> error while testing my AngularJS/nodejs project

After launching the project to check out the login/registration interface, the following screen is displayed: Login/Registration: My code already includes Bootstrap and jQuery: <script type="text/javascript" src="assets/js/jquery.min.js"></scr ...

The Angular model does not automatically refresh when the Space or Enter key is pressed

Having an issue with my editable div and the ng-trim attribute. Even though I have set ng-trim to false, pressing SPACE or ENTER does not increment the string length by one in the div below. Using Angular 1.3.x and wondering if anyone has any ideas on how ...

Need help implementing the disableGutters property on MTableToolbar?

I am currently using react material-table and I would like to customize the default toolbar styles by passing the prop disableGutters={true}, similar to how it's done in material-ui toolbar. Below is the code snippet that I have tried: <MaterialTab ...

Steps for resolving the issue "Error: Module not found 'C:Users odri odejs_paypalsrcindex.js'" in Node.js

As I attempt to launch my Node.js project, I'm running into a module resolution error that reads as follows: PS C:\Users\rodri\nodejs_paypal> npm run dev <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

What is the process for updating a MySQL database by clicking a button?

Hey there, I have a bit of a dilemma. I know that accomplishing this task can't be done solely with PHP; I believe Ajax/Javascript is required. Unfortunately, my knowledge in these areas is quite limited, so I could really use your assistance. Here&a ...

What could be the reason for the Javascript function failing to run?

I need assistance in executing a function called "send()" which includes an AJAX request. This function is located in ajax.js (included in the code snippet) The Ajax success updates the src attribute of my image. The function seems to be working correctly ...

React application utilizing Javascript Geofire and Firebase experiences inconsistencies when instantiating and declaring variables within class-based logic

After following a tutorial on setting up Geofire with Firebase, I encountered an issue when trying to use GeoFire in a separate class file. The GeoFire variable was set successfully in a regular JS code file, but when attempting to do the same within a Geo ...

Getting the value of a CSS variable under <script> in Vue.js

I am working on implementing a Doughnut chart using chartJs in my application. However, I want to set the color of the chart within the <script> tag and retrieve the color from theme/variables.css. In the current code snippet below, there is a hardc ...

Execution of Ajax call fails to occur synchronously

I have created a unique weather website that utilizes the flickr API as well as the yahoo API to gather weather data. However, I am facing an issue where the ajax call from the yahoo API does not retrieve the necessary data in time for the content of the p ...

Problem with UV mapping when adjusting texture size

I am currently working on an application to modify minecraft models. To display the drawn texture mapped on the 3D player model, I am using ThreeJS. However, I'm facing a challenge related to changing the texture size. Initially, the texture is mappe ...

Mastering Fluent UI Web: Adjusting the border radius of a TextField component

I am in the process of creating a custom user input control that includes a TextField, a Dropdown, and a Button. To ensure that the TextField and Dropdown appear as a cohesive unit rather than two separate elements, I attempted to use two specific styles ...