4

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

Pseudo Code:

  1. Inject Jquery into the webpage
  2. Discover the required form.
  3. Update the values, e.g.,


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

I have a new customer who is using Angularjs and this model breaks down as the $scope is obviously being updated "out-of-band". I don't have access to the third party source to make changes, so I was wondering if it is possibly to get a jQuery update to trigger an Angularjs update?

4

3 に答える 3

5

angular.element()を使用して、スコープとngModelControllerを取得できます。

var value = 'theNewValue';
var el = angular.element($('#name'));

el.scope().$apply(function(){
  el.val(value);
  el.controller('ngModel').$setViewValue(el.val());
});

簡単な例を次に示します: http://plnkr.co/edit/OJQQmanwQoFQSgECuqal?p=preview

于 2013-06-03T21:22:25.967 に答える
1

他の回答に同意すると、ダイジェスト フェーズの問題を回避する$timeout代わりに使用することをお勧めします。$apply

@liviu-t レスポンスのように、$element のインジェクターを使用して $timeout サービスを取得します。次に、それを nextTick() 関数として使用します。実際には (2 番目の引数が 0 または欠落している場合) とほぼ同等ですが、ダイジェストのnextTick()で呼び出す必要がある $apply とは異なり、常にダイジェスト フェーズで引数を実行するという違いがあります。

于 2013-06-04T23:56:04.490 に答える
0

実際のケースによっては、少し複雑です。私の解決策は、要素がdom Readyで利用可能であり、パーシャルを使用してangularによってロードされていないことを前提としています。デモ

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>

リンク

  1. $インジェクター
  2. $パース
于 2013-06-03T21:10:25.883 に答える