1

サーバーから受け取った新しい html を埋め込むことはできますが、後でそれをモデルにバインドする必要があります。挿入して表示してから5秒後にコンパイルしても、htmlはモデルにバインドされません。

簡単に例を挙げてみましょう

function coolController($scope, $http, $log, $sce, $compile, $timeout){
$scope.message = {
        error: 'Kernel panic! :)',
        otherInfo: ''
    }

    $scope.form = $sce.trustAsHtml('<div></div>');

    $scope.Init = function(){
        $http({
            method: 'GET',
            url: helper.url('/form')
        }).
        success(function(data, status, headers, config) {
            $scope.form = $sce.trustAsHtml(data);
            $timeout(function(){
            $compile(angular.element('#elemThatContainsTheNewHTML'))($scope);
            }, 2500);

        }).
        error(function(data, status, headers, config) {
            $scope.message.error = data;            
        });
    }
}

htmlが

<div>
My cool error: {{ message.error }}
</div>

埋め込まれている場所は次のようになります。

<div ng-controller="coolController">
    <h4>Hello???</h4>

    <div ng-init="Init()">
      <span class="alert-error" ng-if="errorMessage.length > 0">{{errorMessage}}</span>
    </div>

    <div id="elemThatContainsTheNewHTML" class="viewContent" ng-bind-html="form">
    </div>
</div>

html は正しく埋め込まれていますが、モデルにバインドしたいと考えています。

4

2 に答える 2

1

私は同じ問題を抱えていて、html コンテンツを再レンダリングする angular ディレクティブを作成します。ディレクティブのコードは次のとおりです。

指令:

app.directive('bindUnsafeHtml', ['$compile', function ($compile) {
      return function(scope, element, attrs) {
            console.log("in directive");
          scope.$watch(
            function(scope) {
              // watch the 'bindUnsafeHtml' expression for changes
              return scope.$eval(attrs.bindUnsafeHtml);
            },
            function(value) {
              // when the 'bindUnsafeHtml' expression changes
              // assign it into the current DOM
              element.html(value);

              // compile the new DOM and link it to the current
              // scope.
              // NOTE: we only compile .childNodes so that
              // we don't get into infinite loop compiling ourselves
              $compile(element.contents())(scope);
            }
        );
    };

}]);

HTML:

<div bind-unsafe-html="form">//your scope data variable which wil assign inn controller
</div>

angularJs プロジェクトを構成するディレクティブをインポートすることを忘れないでください。これが役立つことを願っています。

于 2014-03-22T04:53:45.163 に答える