Force soft update fields using Angularjs

I have an application, call it "form-filler", which works with many sites using jQuery to automatically update fields.

Pseudocode:

  • Embed jquery on web page
  • Open the required form.
  • Refresh values ​​e.g.


$(document).ready(function) { $('#id').val("some value"); } 

I have a new client that uses Angularjs, and this model breaks because the $ volume is obviously being updated "out of range". I don’t have access to a third-party source for making changes, so I was wondering if it is possible to get a jQuery update to run the Angularjs update?

+4
source share
3 answers

You can use angular.element () to capture the area and ngModelController :

 var value = 'theNewValue'; var el = angular.element($('#name')); el.scope().$apply(function(){ el.val(value); el.controller('ngModel').$setViewValue(el.val()); }); 

Here is a simple example: http://plnkr.co/edit/OJQQmanwQoFQSgECuqal?p=preview

+5
source

Agreeing with the other answers, I suggest using $timeout instead of $apply to avoid problems with the digest phase.

As in @ liviu-t's answer, get a $ timeout service using the $ element injector. Then use it as the nextTick () function. This is actually (with the second argument 0 or absent), almost equivalent to nextTick() , with the difference that it always executes its argument in the digest phase, unlike $ apply, which should be called outside the digest.

+1
source

This is a bit more complicated depending on the actual case. My solution assumes elements are available in dom ready and not loaded using angular using partials. Demo

Js

 function setAngularValue($elem, value) { var scope = $elem.scope(); var ngModelName = $elem.attr('ng-model'); if(ngModelName) { var $injector = $elem.injector(); //get the parse service to use on the ng-model var $parse = $injector.get('$parse'); var ngModel = $parse(ngModelName); scope.$apply(function() { //this will allow any ng-model value ex: my.object.value ngModel.assign(scope, value); }); } else { //fallback if there is no model, weird case imho $elem.val(value); } } $(document).ready(function() { var $elem = angular.element('#myJqueryId'); var value = 'some value'; setAngularValue($elem, value); }); 

HTML

 <p>Hello {{my.angular.model}}!</p> <input id="myJqueryId" ng-model="my.angular.model"></input> 

LINK

0
source

Source: https://habr.com/ru/post/1484278/


All Articles