84

私はjQueryとAngularJSの両方を使用してAjaxアプリに取り組んでいます。

jQueryの関数を使用してdivのコンテンツ(AngularJSバインディングを含む)を更新するhtmlと、AngularJSバインディングが機能しません。

以下は私がやろうとしていることのコードです:

$(document).ready(function() {
  $("#refreshButton").click(function() {
    $("#dynamicContent").html("<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>")
  });
});
</style><script src="http://docs.angularjs.org/angular-1.0.1.min.js"></script><style>.ng-invalid {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="">
  <div id='dynamicContent'>
    <button ng-click="count = count + 1" ng-init="count=0">
        Increment
      </button>
    <span>count: {{count}} </span>
  </div>


  <button id='refreshButton'>
    Refresh
  </button>
</div>

IDを持つdiv内に動的コンテンツがあり、#dynamicContent更新がクリックされたときにこのdivのコンテンツを更新する更新ボタンがあります。コンテンツを更新しない場合、インクリメントは期待どおりに機能しますが、更新後、AngularJSバインディングは機能しなくなります。

これはAngularJSでは有効ではない可能性がありますが、最初はjQueryを使用してアプリケーションを構築し、後でAngularJSを使用し始めたため、すべてをAngularJSに移行することはできません。AngularJSでこれを機能させるための助けをいただければ幸いです。

4

3 に答える 3

115

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

于 2012-08-02T15:17:33.460 に答える
18

@jwizeの回答への追加

angular.element(document).injector()エラーが発生していたためinjector is not defined 、AJAX 呼び出し後または jQuery を使用して DOM が変更されたときに実行できる関数を作成しました。

  function compileAngularElement( elSelector) {

        var elSelector = (typeof elSelector == 'string') ? elSelector : null ;  
            // The new element to be added
        if (elSelector != null ) {
            var $div = $( elSelector );

                // The parent of the new element
                var $target = $("[ng-app]");

              angular.element($target).injector().invoke(['$compile', function ($compile) {
                        var $scope = angular.element($target).scope();
                        $compile($div)($scope);
                        // Finally, refresh the watch expressions in the new element
                        $scope.$apply();
                    }]);
            }

        }

新しい要素のセレクターを渡すだけで使用できます。このような

compileAngularElement( '.user' ) ; 
于 2015-11-05T07:26:26.340 に答える