0

かなり簡単な解決策があることを願っています。

ファイルから HTML をロードするディレクティブを設定しました。次に、Angular を使用してその HTML をコンパイルすることになっています。ディレクティブ:

angular.module('wc.directives', [], function($compileProvider) {
  $compileProvider.directive('view', function($compile) {
    return function(scope, element, attrs) {
      scope.$watch(
        function(scope) {
           // watch the 'view' expression for changes
          return scope.$eval(attrs.view);
        },
        function(value) {
          // when the 'view' expression changes
          $.ajax({
            url: '/partials/' + value,
            success: function(data) {
              element.html(data);
              $compile(element.contents())(scope);
            }
          });
        }
      );
    };
  });
});

これがロードするはずの何かの例 (ジェイド)

input#nameInput.nameField(ng-model='name', type='text')
h1 {{ name }}

ページが読み込まれると、{{ name }} が表示されます。ただし、テキスト フィールドに入力を開始すると、{{ name }} は入力内容に合わせて更新されます。

element.htmland$compileステートメントが ajax コールバック内にない場合、successすべてが期待どおりにコンパイルされます。

4

2 に答える 2

2

jQuery のajax. AngularJS$httpを優先してドロップすると、呼び出す必要がなくなります$apply(呼び出し$httpます!)。

要するに、jQuery を使用する特別な理由がない限り、ajaxそれを削除して$http代わりに使用してください。

于 2013-06-24T15:55:21.750 に答える
0

予想通り、それは簡単な解決策でした。

ステートメントscope.$apply();の後に追加する必要がありました。$compile

編集:より良い解決策は、を使用すること$httpです。最終的な作業コードは次のとおりです。

angular.module('wc.directives', [], function($compileProvider) {
  $compileProvider.directive('view', function($compile, $http) {
    return function(scope, element, attrs) {
      scope.$watch(
        function(scope) {
           // watch the 'view' expression for changes
          return scope.$eval(attrs.view);
        },
        function(value) {
          // when the 'view' expression changes
          if (value !== null) {
            $http.get('/partials/' + value).success(function(data) {
              element.html(data);
              $compile(element.contents())(scope);
            });
          }
        }
      );
    };
  });
});
于 2013-06-24T00:24:54.497 に答える