Execute a script once the AngularJS view has finished loading

Just starting out with AngularJS and I've encountered an issue;

I'm populating part of my view with HTML from a variable in my controller:

<div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>

Everything works as expected until I try to execute a script. The script is displayed, but it does not run. I suspect that the problem arises because the view is populated with my controller variable after the page has loaded, causing the script not to execute. The reason I am using a variable in my controller to store the script is because I need to retrieve the script from elsewhere and it changes frequently.

Is this a suitable approach for running my script?

Here's a snippet of my code:

View:

<div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>

Controller:

.controller('browseCtrl', function($scope,$sce) {

  $scope.video = '<div id="idxx1" style="width: 460px; height: 290px;" itemprop="video" itemscope itemtype="http://schema.org/VideoObject"></div><script>addeere3ejs("idxx1",  "172653", "24431581", "1_fq2w6oc2");</script>';

  $scope.deliberatelyTrustDangerousSnippet = function() {
    return $sce.trustAsHtml($scope.video);
  };
})

If you're unclear about my question, feel free to ask for clarification.

Answer №1

To execute a script when the view is loaded, you can utilize the viewContentLoaded event within your controller.

$scope.$on('$viewContentLoaded', function(){
 // Code to run after the view is loaded.
});

It's uncertain whether ng-bind-html allows running a script in that manner. You might have to enclose it in Angular's brackets for automatic execution upon loading.

 <div ng-bind-html="{{trustDangerousCode()}}"></div>

Answer №2

To solve the issue, I implemented a workaround by executing a $scope function utilizing predefined variable(s) that are expected to undergo changes:

{{runFunction(results)}}

Subsequently, within your controller, you can incorporate a method like so:

$scope.runFunction = function (obj) {
        execute_external_methods();
    }

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

Is it common practice to provide a callback function as a parameter for an asynchronous function and then wrap it again?

app.js import test from "./asyncTest"; test().then((result)=>{ //handle my result }); asyncTest.js const test = async cb => { let data = await otherPromise(); let debounce = _.debounce(() => { fetch("https://jsonplaceholde ...

What steps do I need to take in order to develop a cross-platform icon using React Native

Currently in the process of creating a signup form, I am looking to incorporate icons that will display differently based on the platform being used. For example, when utilizing Ionicons, I would like the icon to appear as ios-person on iOS devices and m ...

Tips on setting up and managing configuration and registering tasks in Grunt

I've been working on a project that involves using grunt to process my Js and SASS files. The issue I'm facing is that every time I need to make a change, I have to run all the tasks in my gruntfile.js, even if it's just for one module or th ...

A guide on implementing the stencilFunc method in Three.js

Is it possible to utilize stencilFunc and stencilOp functions within Three.js? I attempted to incorporate code for a stencil test but encountered issues. var scene = new THREE.Scene(); var renderer = new THREE.WebGLRenderer({ antialias: true, st ...

Server Error: Experiencing an overload of renders. React has set limits on the number of renders to avoid getting caught in an endless loop

I am currently attempting to develop a basic stopwatch application and encountering the following error message. Despite trying various solutions from similar queries, I have not been able to pinpoint the root cause of this issue or resolve it. Below is t ...

Node.js: implementing method overriding

I'm currently exploring the most effective method to override a function in a custom module using node.js. As part of my project, I am developing a custom middleware that will assist me in automatically loading various custom modules such as security ...

Unclear when notifying div content

After creating a PHP page, I encountered an issue while trying to select the inner text of a div and alert it with jQuery. Instead of getting the expected result, it keeps alerting "undefined." What could possibly be causing this? Here is the code snippet ...

Unable to generate a vertical navigation bar

When attempting to create a vertical menu, the final result doesn't align as expected. https://i.stack.imgur.com/2ok47.jpg This is the current code being used: $("#example-one").append("<li id='magic-line'></li>") ...

Strategies for resolving type issues in NextJs with Typescript

In my project using Next.js with TypeScript, I encountered an issue while trying to utilize the skipLibCheck = false property for enhanced checking. This additional check caused the build process to break, resulting in the following error: Error info - U ...

Failure to send Websocket connection

Currently working on PHP, here's a snippet: $room_array = array(); $room_array[0] = 'room-list'; $room_array['info'] = array('room_name' => $room['room_name'], 'owner' => $username['usernam ...

Sending images as a base64 string from a Titanium app to a Ruby on Rails web service

I am encountering an issue when trying to upload an image from an app that has been converted into a base64 string to a Ruby on Rails server. The app is developed using Titanium. However, after retrieving and decoding the image string back into an image, ...

The variable _spPageContextInfo has not been defined, resulting in a ReferenceError

The code in my JavaScript file looks like this: var configNews = { url:_spPageContextInfo.webAbsoluteUrl, newsLibrary: 'DEMONews', listId: '' }; // Attempting to retrieve the List ID $.ajax({ url: configNews.url + "/_a ...

Utilize the latest REDUX state within a React component's function

I'm currently facing an issue in my React application where I am struggling to access the updated state from within a function. Here is a simplified version of my problem: I have a custom React Component to which I pass a variable representing the st ...

Issues with dynamically generating buttons using Ajax and Javascript technology

In order to dynamically create buttons based on the contents of a text file during the onload event, I have written a JavaScript function. However, despite being able to read the file and using alert messages to verify the correctness of the variable &apos ...

Managing the jQuery.noConflict function

Upon review, I noticed that the scripts I inherited start like this: var $j = jQuery.noConflict(); The purpose behind this code is not clear to me. While I understand the intent is to avoid conflicts, I am uncertain about the specific conflict it aims to ...

Reset all divs to their default state except for the one that is currently active using jQuery

Here's the plan for my script: Once a user clicks on a "learn more" button, it will reveal the relevant information in the corresponding box. I'm aiming to implement a feature where if you click on another "learn more" button while one box is a ...

How can I update an image source using JavaScript in a Django project?

Is it possible to dynamically change the image src using onclick without relying on hard paths or Django template tags? I have concerns that this may not be best practice. How can I implement a method to inject/change the ""{% static 'indv_proj&b ...

Utilizing UI Bootstrap Pagination with ng-repeat to enhance the user experience of navigating through a dynamically generated table

Struggling with incorporating pagination into my Angular app using uib-pagination. I can't seem to figure out the correct approach. HTML <table id="mytable" class="table table-striped"> <thead> <tr class="table-head"> & ...

What is the method for including the `meta:redirect` or `<meta http-equiv="refresh" content="0; url=http://example.com" />` in the metadata object for Next.js version 13?

In order to redirect users from one of my pages, I previously utilized the redirect metatag. However, I am unable to locate similar options within the metadata API in Next.js 13 for the appRouter. ...

The hidden attribute of UIWebView and its interplay with JavaScript

In the webViewDidStartLoad method, I hide the webview. Then a request is made. In the webViewDidFinishLoad method, I use stringByEvaluatingJavaScriptFromString. Finally, the webview is shown again. However, when I run the app, I can still see how the Java ...