我想使用
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的引用
>获取您希望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) { ... }]);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。