Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何使用angularjs with greasemonkey来修改网页?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用 angularjs和greasemonkey修改网页的行为.我想知道,最好的方法是什么?在我编写一些角度代码之前,@R_657_10675@用 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的引用
>获取您希望HTML代码连接到的AngularJS范围的引用
>将带有ng- *属性HTML代码在字符串中,并在其上调用$compile和范围.
>获取结果并使用通常的jQuery风格方式将其放入页面.

为了说明,这里是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使用传递给它的函数的参数名称
确定要注入的内容,如果您使用的是更改参数名称的minifier,这将会中断.

为避免这种情况,您可以更换

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

与形式

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

如果minifier将参数名称更改为$compile之外的其他内容,则不会中断.

大佬总结

以上是大佬教程为你收集整理的如何使用angularjs with greasemonkey来修改网页?全部内容,希望文章能够帮你解决如何使用angularjs with greasemonkey来修改网页?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。