在 chrome 扩展中使用页面的 angular JS [英] Using page's angular JS in chrome extension

查看:36
本文介绍了在 chrome 扩展中使用页面的 angular JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HTML 页面,其中有一些使用 Angular 配置的 DOM.现在我正在构建一个 chrome 扩展来修改文本框中的值.element.value= newValue 将不起作用,因为文本框是用 Angular 设计的.阅读一些资源后,我开始知道我需要对元素的范围进行更改.我尝试在扩展程序中执行此操作.

I've a HTML page which has some DOM configured with Angular. Now I'm building a chrome extension to modifying value in a text box. element.value= newValue will not work as the text box is designed with Angular. After reading some resources, I came to know that I need to do the changes to the scope of the element. I tried doing this in the extension.

var eleScope = window.angular.element(document.querySelector('.textbox')).scope();
eleScope.$apply(function() {
  eleScope.item.request.box = newValue;
});

这似乎没有按预期工作.当我更深入地挖掘问题时,我才知道 window 范围内的 angular 没有得到正确的范围.

This doesn't seem to work as intended. When I dug into the problem more deeply, I came to know that the angular in the scope of window was not getting the right scope.

我还尝试从我的扩展中注入 angular.js 并直接使用 angular.element ,这似乎也没有解决问题.

I also tried to inject angular.js from my extension and using angular.element directly which also doesn't seem to solve the problem.

我是不是遗漏了什么.感谢您的回复.

Am I missing something. Appreciate your replies.

推荐答案

嗯.. 实际上,您应该能够使用 vanilla Javascript 或 JQuery 更改值,并且不需要更新范围,因为它是双向绑定IE.更新视图会更新模型,反之亦然.

Hmm.. Actually you should be just able to change the value using vanilla Javascript or JQuery and should not need to update the scope as it is two-way binding ie. Updating the view updates the model and vice-versa.

模型不更新的唯一原因是观察者更新模型仅在点击"或输入"等特​​定事件时触发.

The only reason why the model does not update is because the watchers to update the model trigger only on particular events like "click" or "input".

所以这里的解决方案是手动触发这些事件.这可以通过:

So the solution here would be to manually trigger these events. This can be do by:

// the selector used is based on your example.
var elementTOUpdate = $('.textbox');
input.val('new-value');
input.trigger('input');

最后一条语句将触发输入"事件(将触发角度观察器)的元素上的所有处理程序并更新范围.有关触发功能的更多信息:http://api.jquery.com/trigger/

The last statement will trigger all the handlers on the element for the "input" event ( which will fire the angular watchers ) and update the scope. More info on the trigger function: http://api.jquery.com/trigger/

这篇关于在 chrome 扩展中使用页面的 angular JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆