如何使用angularjs with greasemonkey来修改网页?
我想使用
angularjs和greasemonkey修改网页的行为.我想知道,最好的方法是什么?在我编写一些角度代码之前,我应该使用
jquery向DOM元素注入像“ng- *”这样的属性吗?或者我可以坚持使用angularjs?
谢谢. 解决方法
关于从
JavaScript代码动态修改DOM中的AngularJS内容的一般答案如下:
AngularJS + JQuery : How to get dynamic content working in angularjs 总而言之,当你从JavaScript代码中将ng- *属性放入DOM时,它们不会自动被连接起来;但AngularJS提供了$compile函数,用于通过JavaScript中的AngularJS属性连接新的HTML内容. 那么当谈到Greasemonkey / Userscript时,这意味着什么呢? 出于此目的,我假设您的Greasemonkey脚本正在修改已使用AngularJS的现有页面,并且您要添加的AngularJS内容使用该页面上已有的AngularJS范围中的一些变量或函数. 出于这些目的: >从AngularJS的动态注入系统获取$compile的引用 为了说明,这里是CERN’s Particle Clicker game的一个小脚本,它在“工人”部分下添加了一个统计数据. $(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(function($compile) { ... }); 与形式 .invoke(['$compile',function($compile) { ... }]); 如果minifier将参数名称更改为$compile之外的其他内容,则不会中断. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |