2

次の角度設定があります。

var app = angular.module('app', []);

app.filter('unsafe', function($sce) {
  return $sce.trustAsHtml;
});

app.controller('SearchController', ['$scope', '$http', function($scope, $http) {
  $scope.searchString = '';
  $scope.searchType = 'Artist';
  $scope.updateHtml = function() {
    $http.get('/search', {
      params: {
        searchString: $scope.searchString,
        searchType: $scope.searchType
      }
    }).success(function(data) {
      $scope.html = data;
    }).error(function(err){
      $scope.html = err;
    });
  };
  $scope.updateHtml(); 
}]);

app.directive('searchDirective', function() {
  return {
    restrict: 'A',
    transclude: true,
    template: '<div ng-bind-html="html | unsafe" ng-transclude></div>'
  };
});

コントローラーの ajax を介して生の html マークアップを取得し、@scope.html. ディレクティブでは、この html が を通じて DOM に挿入されますng-bind-html

html (jade) は次のようになります。

#search(ng-controller="SearchController" search-directive)

それは基本的に機能します。しかし、含まれているこのhtmlの中に、私は{{searchType}}解決したいようなトランスクルーシブなコンテンツがあります。残念ながらそうではなく、ブラウザに「{{searchType}}」と表示されます。トランスクルージョンを機能させるために何を変更できますか?

$compileとについて読みまし$transcludeたが、使い方がわかりません。問題の解決に役立つかどうかもわかりません。どうも!

4

1 に答える 1

2

パトリックの助けを借りて、私はそれを解決することができました. コントローラーを

 app.controller('SearchController', ['$scope', '$http', '$interpolate',  
              function($scope, $http, $interpolate) {
    $scope.searchString = '';
    $scope.searchType = 'Artist';
    $scope.updateHtml = function() {
      $http.get('/search', {
        params: {
          searchString: $scope.searchString,
          searchType: $scope.searchType
        }
      }).success(function(data) {
        $scope.html = $interpolate(data)($scope); // <<-- difference here
      }).error(function(err){
        $scope.html = err;
      });
    };
    $scope.updateHtml(); 
  }]);

そして今、私のhtmlは渡されたスコープに基づいて補間されています。ありがとう!

edit: $interpolate DOM をレンダリングし、スコープを介して解析するためだけです。プレーンな html を返すだけです。Angular コードを含む完全に機能する html テンプレートを実際に取得する必要がある場合は、$compile. この回答$interpolate$compileとの違いを整理するのに非常に役立ちました$parse

于 2014-12-08T20:19:13.457 に答える