我想修改使用angularjs和Greasemonkey的網頁的行爲。我想知道,最好的方法是什麼?我應該使用jQuery注入像「NG-*」到DOM元素之前,我可以寫一些代碼的角度屬性?或者我可以單獨堅持angularjs?如何使用angularjs與Greasemonkey的修改網頁?
謝謝。
我想修改使用angularjs和Greasemonkey的網頁的行爲。我想知道,最好的方法是什麼?我應該使用jQuery注入像「NG-*」到DOM元素之前,我可以寫一些代碼的角度屬性?或者我可以單獨堅持angularjs?如何使用angularjs與Greasemonkey的修改網頁?
謝謝。
有大約從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範圍中的一些變量或函數。
對於那些目的:
$compile
參考獲取到你希望你的HTML代碼連接到ng-*
HTML代碼中的字符串屬性和調用它和範圍$compile
。舉例來說,這裏有一個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) { ... });
。