2014-03-14 34 views

回答

4

有大約從JavaScript代碼在這裏,動態地修改AngularJS內容DOM中的一般的答案:

AngularJS + JQuery : How to get dynamic content working in angularjs

綜上所述,當你把ng-*屬性爲從JavaScript代碼的DOM,他們不會自動掛鉤;但AngularJS提供了與AngularJS掛鉤新的HTML內容從JavaScript屬性$compile功能。

那麼這是什麼意思,當涉及到的Greasemonkey/Userscript?

爲此,我假設您的Greasemonkey腳本正在修改已經使用AngularJS的現有頁面,並且您要添加的AngularJS內容在該頁面上已經使用了AngularJS範圍中的一些變量或函數。

對於那些目的:

  1. 獲得來自AngularJS」動態噴射系統
  2. $compile參考獲取到你希望你的HTML代碼連接到
  3. 把AngularJS範圍引用您的與ng-* HTML代碼中的字符串屬性和調用它和範圍$compile
  4. 取得這個結果,並使用通常的jQuery風格的方式把它放到頁面中。

舉例來說,這裏有一個CERN's Particle Clicker game的小腳本,它在'workers'部分下添加一個stat。

$(function() { // Once the page is done loading... 

    // Using jQuery, get the parts of the page we want to add the AngularJS content to 
    var mediaList = $('ul.media-list');  
    var medias = $('li.media', mediaList); 

    // A string with a fragment of HTML with AngularJS attributes that we want to add. 
    // w is an existing object in the AngularJS scope of the 
    // <li class="media"> tags that has properties rate and cost. 
    var content = '<p>dps/MJTN = <span ng-bind="w.rate/w.cost * 1000000 | number:2"></span></p>'; 

    // Invoke a function through the injector so it gets access to $compile ** 
    angular.element(document).injector().invoke(function($compile) { 

     angular.forEach(medias, function(media) { 

      // Get the AngularJS scope we want our fragment to see 
      var scope = angular.element(media).scope(); 

      // Pass our fragment content to $compile, 
      // and call the function that $compile returns with the scope. 
      var compiledContent = $compile(content)(scope); 

      // Put the output of the compilation in to the page using jQuery 
      $('p', media).after(compiledContent); 

     }); 
    }); 

}); 

**注:就像使用它的依賴注入任何AngularJS功能, .invoke使用您傳遞給它的函數的參數名稱 確定注入什麼,這將打破,如果您使用的是minifier改變參數名稱。

爲了避免這種情況,你可以用形式

.invoke(['$compile', function($compile) { ... }]); 

如果minifier改變參數名稱比$compile其他一些東西,不會打破取代

.invoke(function($compile) { ... });