Implement Angular.js on a fresh DOM element within a Content Script in a Chrome Extension

After spending quite some time on this, I still haven't made much progress.

I'm attempting to incorporate angular functionality (such as ng-repeats and data binding) into the red box that pops up when text is double-clicked on any webpage. Unfortunately, I'm struggling with how to actually integrate Angular with the text box in this specific scenario.

While using angular in a badge popup in Chrome or on options pages seems straightforward, applying it in this context has proven to be a challenge.

inject.js (included as a content script in the manifest file below)

    var displayPopup = function(event) {

    var mydiv = document.createElement('div'); 
    var $div = $('#divid').closest('.sentence');
    mydiv.innerHTML = getSelectionText();
    mydiv.innerHTML += currentSentence.innerHTML;

        //This is where I would like to implement some angular functionality
        mydiv.innerHTML += '<div ng-app="myApp" scroll-to-me><input type="text" ng-model="data.test"><div ng-model="data.test">{{data.test}}</div></div>';



    mydiv.id = "popup";
    mydiv.style.position = "fixed";
    mydiv.style.top = event.clientY + "px";
    mydiv.style.left = event.clientX + "px";
    mydiv.style.border = "4px solid #d00";
    mydiv.style.background = "#fcc";

        $("body").append(mydiv);

    $.getJSON('http://local.wordly.com:3000/words/definitions/test', function(data) {
      console.log(data);
    });
  }

The content script array in my manifest.json looks like:

"content_scripts": [
    {
      "matches": [
        "https://www.google.com/*"
      ],
      "css": [
        "src/inject/inject.css"
      ]
    },
    {
      "matches": [
        "http://*/*", 
        "https://*/*"
      ],
      "js": [
        "js/angular/angular.js", "app.js", "js/jquery/jquery.js", "src/inject/inject.js"
      ]
    }
  ]

Also included in the manifest is app.js, which contains a basic skeletal app setup to kickstart the project.

var myApp = angular.module("myApp", []);

myApp.factory('Data', function(){
    //return {message: "I'm data from a service"};
});

myApp.controller("SecondCtrl", function($scope, $http){

});

Answer №1

If you're adding the markup after the page has loaded, you will need to manually bootstrap in Angular. The ng-app directive will only run if it's present during the initial page load. After that, you can use angular.bootstrap to pass the module name:

angular.bootstrap(myDiv, ['myApp'])

Check out this example.

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

How to effortlessly convert a JSON string into a JavaScript object

Hello everyone, I am working with DynamoDB and need to parse the JSON Object that is returned from a call in order to retrieve the password hash field. jsonString = JSON.stringify(data) console.log(jsonString) This is what the output looks like: {"Count ...

Is it possible to insert a second hyperlink into a JavaScript-occupied anchor?

Check out my reference page at: To change the content in a 'containerarea' div, I am utilizing Dynamic Drive's "Dynamic Ajax" script. Below is an example of the anchor code used: <a href="javascript:ajaxpage('videos-maintenance/app ...

Surprising outcome of Vue

As a newcomer to vue.js, I am struggling with a side effect issue in a computed property. The unexpected side effect error is popping up when running the code below, and ESlint is pointing it out in the console. I understand the concept of side effects, bu ...

Contrast in the way an angular controller integrates $scope

I am brand new to using Angular. I have noticed two different ways of passing the $scope object to an angular controller: app.controller("myCtrl", function($scope) { ... }); app.controller('myCtrl', ['$scope', function($scope) { ... } ...

What is the best way to pass around shared constants within NodeJS modules?

My current approach involves the following steps: foo.js const FOO = 5; module.exports = { FOO: FOO }; I then use it in bar.js: var foo = require('foo'); foo.FOO; // 5 However, I'm wondering if there is a more efficient way to hand ...

The attribute 'xxx' is not found within the 'Readonly<{}>' type

I am currently in the process of writing tests for a React Typescript component. App.tsx: import * as React from 'react'; import { Button } from 'react-bootstrap'; interface Igift { id: number; } interface IAppState { gifts: Igi ...

An Uncaught TypeError is thrown when using setTimeout()

Currently, I am configuring the .hover() function in the code below: $(".portfolio_overlay").hover(function(){ setTimeout(function(){ $(this).fadeTo(750, 0.72, "swing", function(){}); }); }); An error is being displayed on the console: U ...

An issue encountered while implementing a post method with fetch and Express

I'm just starting out, so I hope my question isn't too basic. My goal is to send a longitude and latitude from client-side JavaScript to a Node.js server using Fetch and Express.js. Below is the HTML code snippet: <!DOCTYPE html> <html ...

Tips for showing an error message on angularjs(404)

Hey there! Currently, I'm developing an AngularJS application that utilizes a web API as the front end. In instances where a user lacks specific permissions, I handle this by returning an HttpResponseMessage containing a custom error message. var mes ...

Tips for creating a JSON cross-domain call in PHP

Hello, I'm just starting to dive into JSON cross domain. I've encountered an issue that I need help with. I am trying to make a cross-domain call to PHP using JSON, but I keep encountering errors. Here is a snippet of the code that I'm worki ...

Refreshing the dat.gui variable is like giving it a fresh

In the dat.gui interface, there is a dropdown list that allows users to select a number. Once a number is chosen, the jumpSwitcher will correspond to that number. The goal is to replace each list with items specific to the number chosen for Starsystem. ht ...

Turn off wss for ASP.NET Core Hot Reload functionality

Currently, I am utilizing ASP.NET Core's hot reload functionality. It attempts to establish connections with two websockets: ws and wss. The ws connection is successful and enables hot reload to function properly. However, since my local development ...

Upon returning to the website homepage from another page, the JavaScript animation ceases

I implemented a unique typewriter animation on my homepage by utilizing code from this source and making minor HTML edits to customize the content. https://codepen.io/hi-im-si/pen/DHoup. <h5> <body>Hello! I am Jane.</body> < ...

What is the best way to incorporate this interaction model using jQuery?

I am exploring the possibility of implementing a unique interaction model using jQuery. If a user is typing on a page and enters three exclamation points in a row ("!!!"), I want jQuery to take action. Once three exclamation points are detected, I wa ...

An efficient JavaScript regular expression pattern that allows for both alphanumeric and special characters

Looking for a javascript regex that allows alphanumeric and special characters exclusively. The following regex was attempted but did not work: /^(?!.*(<|>)).*[a-zA-Z0-9 \\\\@!#$%^&*()_+-={}:;'\",.?|\[\&bs ...

[webpack]: npm ERROR! Call stack size limitation exceeded

While trying to install webpack using npm i -D webpack, an error is encountered as shown below. npm ERR! Maximum call stack size exceeded npm ERR! A complete log of this run can be found in: npm ERR! /Users/shobhuiy1/.npm/_logs/2019-02-05T10_31_29_46 ...

Combining arrays of objects in VueJS

I am working with 2 components: parent component (using vue-bootstrap modal with a vue-bootstrap table) child component (utilizing vue-bootstrap modal with a form) Issue: When I submit the form in the child component, it successfully adds the object to ...

Connect the B-Button to an input file using BootstrapVue

I am attempting to create an input file button within a v-for loop without using the b-form-file tag. Despite trying various solutions, none of them have worked for me. Here is the code I have so far: <b-button @click="selectFile()" variant=& ...

Navigating through paginated data can be made easier by using Backbone.PageableCollection in conjunction with a personalized

I have developed an application that interacts with a database known as LeanCloud. Currently, I have configured a page to display all the users stored in the database. However, LeanCloud has a limitation where only 100 pieces of data can be retrieved per r ...

Automatically close the menu in ReactJS when transitioning to a new page

I have created a nested menu, but I am facing an issue with it. Here is the structure: Parent_Menu Parent1 > Child_Menu1 > Child_Menu2 Parent2 Currently, when I click on, for example, Child_Menu1, I am redirected to the correct page ...