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

Combining two JSON objects with sailsjs-nodejs to create a single merged object

Hello everyone, I am a beginner with Sailsjs-Nodejs. Currently, I have two JSON Objects in my controller that I need to merge/join in order to create a third object to send as a response. The output when using res.send(obj1) is: [ { total_fare: "37 ...

How to automatically open JQuery Accordion panels when the page loads

My Accordion loads with the 1st panel open upon page load, but I am looking for a way to have the entire Accordion closed by default. Any help or suggestions on how to achieve this would be highly appreciated. Thank you for your assistance. FIDDLE http:// ...

Utilize resources from webpack's bundled npm package assets

I've been racking my brain over this issue for quite some time now, and I'm starting to wonder if it's even achievable. Any assistance on this matter would be greatly appreciated! The npm dilemma I have an npm package that serves as a coll ...

able to utilize service within a loop

import { Component, Input, Output, OnInit, OnChanges } from '@angular/core'; import { ViewComponent } from '../view/view.component'; import { HitoService } from '../../services/hito.service'; @Component({ selector: 'ap ...

The Highchart column chart is triggering the drilldown event multiple times

I have created a column chart using Highchart and I am facing an issue with the drilldown functionality. Whenever I click on a bar multiple times, the drilldown event triggers multiple times as well. This results in the drilldown event being triggered repe ...

The CSRF token in Laravel Blade seems to be unreachable by Vue

Having a blade with the following code snippet. <meta name="csrf-token" content="{{ csrf_token() }}"> <covid-form> </covid-form> Inside the covid-form component, there is a form structure like this: <form @submit.prevent="send"&g ...

Guide on making a pop-up element appear above an MD dialog box

I'm currently working with AngularJs 1.7 and have developed a dropdown element that I would like to include in an md-dialog. However, the issue I'm facing is that my element (my-popup) always stays within the boundaries of the md-dialog - similar ...

The checkbox will be automatically checked whenever there is any modification in the textbox

I'm currently working on a Grid view with a checkbox and two textboxes. What I want is for the checkbox to be automatically checked whenever there is a change in one of the textbox values, for example switching from 0 to 1. This project is being devel ...

Challenges encountered with input outcomes

I am facing an issue with input results. I have a button that triggers a function to check for empty input fields. However, when I click the button, it always falls into the last if statement and displays as if the fields are not empty. I have already att ...

Mastering TypeScript in Router Configuration

I am currently working with a standard router setup. type Routes = '/' | '/achievements' | ... ; This helps in identifying the routers present in the project. However, I am faced with a new challenge of creating an array that includes ...

Having trouble making a call to my RESTful service from an AngularJS application using $http

I am having trouble with reading JSON data from a REST webservice using AngularJS $http. I have a simple REST webservice located in a separate project which returns JSON. However, when I attempt to access the REST service from Angular, it results in an err ...

Adding a Resource Bundle to a Vue project

I am looking to integrate the ResourceBundle package into my Vue project. After installing it with the following command: npm install resource-bundle I discovered these exported functions in the index.js file of the ResourceBundle package: export functi ...

Is it possible to create a custom options array in React-Select?

I've been working with react-select using the package from . The required format for the options prop is {value:something, label:something}. I have a list of objects with additional key-value pairs and I'm wondering if there's a way to avoi ...

The AngularJS DOM seems to be updating, but the screen is not reflecting any changes. Uncertain about the next steps to take

I am experiencing a perplexing issue where, despite ng-click updating the expected scope variables and the changes being visible in the DOM via the Chrome debugger, the altered DOM elements are not redrawn in the browser. This anomaly occurs consistently o ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...

Add a third-party library file to Visual Studio

I'm currently working in Visual Studios and attempting to utilize the library provided at . However, I am encountering difficulties when trying to import the library. I have added the file to the project and attempted to use it within the Book.js (Vi ...

Utilizing React JS to Develop Cell Components for a Schedule, Ensuring Teams are Unique within the Same Row

I am currently facing a challenge involving a table that has a fixed number of timeslots (y axis) and pitches (x axis). In addition, I have a collection of match objects with the following structure: Object { id: 3, teamA: "pelt", teamB: "Ranelagh" } Eac ...

Tips for avoiding cropped images on mobile websites:

I recently created a website that looks perfect on desktop but appears cropped on mobile devices. The site in question is doc.awsri.com Here are the images causing the issue: https://i.stack.imgur.com/eRJXU.png The problem arises when viewing it on a ph ...

Tips for accessing nested documents from Firebase in React.js

Here is a snippet of code from my React project: import React, { useState } from "react"; import { db } from "../firebase"; import { collection, Firestore, getDocs } from "firebase/firestore"; function Document() { const ...

"Sparkling div animation with the use of jQuery's .hover() function

<script> $(document).ready(function () { $("#logo_").hide(); $("#logo_learn").hide(); }) function sl() { $("#logo_learn").slideToggle(500); $("#logo_").fadeIn(); } function hl() { $("#logo_learn").slideToggle(500); $("#logo_ ...