简体   繁体   中英

Apply Angular.js to new DOM Element in Chrome Extension Content Script

Okay, so I've been at this for a while.

In the red box, I want to have some angular functionality (ng-repeats, data binding, etc...) This red box appears when text on any webpage is double clicked. However, I can't seem to find out how to actually get angular wired/hooked up to the text box example in the red popup.

It seems fairly trivial to use angular in a badge popup in chrome, as well as on options pages, etc...but I can't seem to get it working in this instance.

在双击文本时将div元素添加到任何网页的DOM的示例

inject.js (which is included as a content script in manifest, below)

    var displayPopup = function(event) {

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

        //Next line is where I want to apply 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);
    });
  }

and my manifest.json content script array 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"
      ]
    }
  ]

and app.js , also included in manifest, for just some skeletal app to get up and running.

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

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

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

});

You need to bootstrap manually if you're injecting the markup after the page loads. Angular will only run ng-app if it's present when the document is loaded. Afterwards, you pass the module name to angular.bootstrap:

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

Example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM