Is it possible to dynamically insert a ng-mouseover in AngularJS using Javascript?

It seems like there is an issue with this code:

var run_div = document.createElement('div');
run_div.className = 'whatever';
run_div.textContent = 'whatever';
run_div.setAttribute('ng-mouseover', 'console.log(\'ei\')');
document.getElementById('main_div').appendChild(run_div);

I believe the problem arises because ng-mouseover needs to be present from the beginning for AngularJS to recognize it (?). Is this correct? Is there a workaround?


(below: UPDATE 1, UPDATE 2, UPDATE 3)

UPDATE 1:
This code functions in a factory, where I invoke the factory method from the controller passing it the $scope:

angular.module('whatever').controller('mycontroller', 
['$scope', '$q', '$window', '$timeout',
function ($scope, $q, $window, $timeout) {

$scope.myfunction= function() {
  myfactory.mymethod($scope);
};

The factory invokes the $compile within its definition:

angular.module('whatever').factory('myfactory', 
['$window', '$q', '$compile',
function($window, $q, $compile) {

...

mymethod = function($scope) {
    var run_div = document.createElement('div');
    run_div.className = 'whatever';
    run_div.textContent = 'whatever';
    run_div.setAttribute('ng-mouseover', 'console.log(\'ei\')');
    document.getElementById('main_div').appendChild(run_div);
}

This approach does not work, leading to an error:

document.getElementById('main_div').appendChild($compile(run_div)($scope));
document.getElementById('main_div').appendChild($compile(run_div)($scope.new()));

or even:

var run_div = angular.element(document.createElement('div'));
run_div.addClass('whatever');
run_div.attr('ng-mouseenter', 'console.log(\'ei\'');
document.getElementById('main_div').appendChild($compile(run_div)($scope));

An error message indicates that the parameter being appended is not a node.

Uncaught (in promise) TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.(…)


UPDATE 2:

Evidence suggests that compiling and appending from a factory does not work, but from a controller it does (refer to answer 2):

http://jsfiddle.net/xsaudasp/1/


UPDATE 3

As demonstrated here, it should work:

http://jsfiddle.net/2uk2qe92/4/

Answer №1

To start, you will need to initialize a new $scope instance specifically for your directive and then utilize the $compile service in order to compile the provided div with that scope:

var customDirectiveScope = $scope.$new();
var compiledCustomDirective = $compile(custom_div)(customDirectiveScope);

Afterwards, you can insert it into the DOM:

angular.element('#my_custom_dir').append(compiledCustomDirective);

Make sure that jQuery is loaded prior to angular so that the jQuery selectors are accessible. If you prefer not to use jQuery, you can opt for jqLite selector instead:

angular.element(document.querySelector('#my_custom_dir')).append(compiledCustomDirective)

For reference, here is a functional jsfiddle showcasing the process: jsfiddle

Answer №2

Before inserting your run_div into the DOM, be sure to compile it:

You can achieve this by utilizing the $compile service in the following manner:

document.getElementById('main_div').appendChild($compile(run_div)($scope));

It is recommended to utilize directives for manipulating the DOM instead of doing so within your controller.

Edit 1:

To create a directive, follow these steps:

.directive('mySpecialElement', function() {
  return {
    restrict: 'E',
    scope: {
      text: '='
    },
    template '<div class="special" ng-mouseover="mouseOver()">{{text}}</div>',
    link: function(scope, element, attrs, tabsCtrl) {
       scope.mouseOver = function(){
          console.log('mouseover');
       }
    }
  };
});

Then, include it in your HTML like this:

<my-special-element text="Dataset.analysis[$index].dataset.name"> </my-special-element>

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

Unable to retrieve information from the API

I have created some Graphs using Graph js and now I want to visualize the data within them. Even though I am able to fetch the data and display it in the console, I am facing issues with displaying it in the actual graph. Despite trying multiple methods, ...

Struggling to concentrate using jQuery?

When the search icon is clicked, I want the focus to be on the input so the user can start typing right away without having to manually click on it. Although I tried using focus(), it doesn't seem to work for this particular input. $('.header__ic ...

AngularJS allows us to dynamically generate button groups

I have a backend that defines datatypes, such as an enumeration for "sex" with values male and female. I need to render these dynamically in angularjs. { 'name': 'sex', 'type': 'enum', 'options': ...

showing the chosen item in a Bootstrap dropdown [limited to the first menu option and using the attr() method]

Is there a way to dynamically display the selected menu option using the bootstrap drop down? Initially, I was able to select the first menu option and apply it to the bootstrap drop-down button. However, I encountered an issue where I cannot change the ...

Incorporating a Drawer and AppBar using Material-UI and React: Dealing with the error message "Unable to access property 'open' of null."

Currently, I am working on developing an app using React and Material-UI. I have successfully implemented the AppBar component, but I am facing difficulties with setting up the Drawer functionality. The main issue I am encountering is an error message sta ...

Error: Failed to clone an object in Electron due to an unhandled promise

I'm in need of assistance with sending files from the main directory to the renderer. Before proceeding, I attempted to check if it was functioning correctly by using console.log(files). However, this resulted in an error message. Can someone please p ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Similar to `util.inspect` in Node.js, Deno also has a function

Is there a utility function in Deno that can stringify an Object or primitive similar to Node.js util.inspect? For instance, if I have a JSON object in Node.js and want to display its contents: > m = {k1:'v1', k2:'v2'} { k1: ' ...

Extracting deeply nested values from a local variable within a view

Here is my current view: <p type="text" disabled='true' class="form-control" > {{selected.timerange}} </p> The value stored in $scope.selected.timerange is: {"available":false,"schedule_start_at":"2015-03-13T00:30:00","schedule_ ...

Tips for passing a state value to a different state when initializing in react js

I need some help with passing a state value called imagesArray to another state named tabData. It seems like the value is coming up as undefined. Below is the code snippet, can you please point out what I might be doing wrong? constructor(props) { s ...

What is the process of handling XML responses using node.js and express?

My task is to handle this using node.js and express: <set id="1" state="0" name="wd"/> I attempted the following approach: xml = require('xml'); res.set('Content-Type', 'text/xml'); res.send(xml('<set id="1" ...

JavaScript: abbreviated way to selectively append an element to an array

Currently, I am in the process of creating a Mocha test for a server at my workplace. When dealing with customer information, I receive two potential phone numbers, with at least one being defined. var homePhone = result.homePhone; var altPhone = ...

Console frozen when executing an async JavaScript script to populate a Mongoose database

I'm currently delving into a personal project and aiming to unravel the intricate logic that is preventing my Node JS process from closing after executing populateTransactions(). My assumption is that the issue lies in not properly closing the DB con ...

Checkbox: Activate button upon checkbox being selected

On my webpage, I have a modal window with 2 checkboxes. I want to enable the send button and change the background color (gray if disabled, red if enabled) when both checkboxes are selected. How can I achieve this effectively? HTML: <form action="" me ...

Do not need to refresh the form

I developed a PHP-based Feedback form that includes a Popup from Foundation 5. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> .auto-style1 { margin-left: 1px; ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

Tips for preventing a React component from scrolling beyond the top of the page

I am looking to achieve a specific behavior with one of my react components when a user scrolls down a page. I want the component to reach the top of the page and stay there without moving any further up. Here is an Imgur link to the 'intranet' ...

Developing a Customized Filtering Mechanism in Angular 8

I have some experience working in web development, but I am relatively new to Angular. My current project involves creating a simple filter for a table's column based on user input. However, I'm facing an issue where typing in a single letter fil ...

Adjust the variable value if the "for" loop encounters an error

In my situation, I have a spreadsheet that contains a script responsible for checking another linked spreadsheet for a customer's name and then returning the associated code. Everything works smoothly when the customer name is found in the "CustomerCo ...

How can you maintain the "link" text in a div while removing the final hyperlink?

I am currently designing a breadcrumb navigation for a website. The breadcrumbs are generated using a templating language before the page is displayed. However, after rendering the page, I need to make some adjustments. Instead of using multiple IF/ELSE s ...