Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

javascript - Using page's angular JS in chrome extension

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;
});

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...