javascript - Angular : using transclude with ng-bind-html

标签 javascript angularjs angularjs-directive transclusion ng-bind-html

我有以下 Angular 设置:

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>'
  };
});

它通过 Controller 中的ajax提取原始html标记并将其存储在@scope.html中。在指令中,该 html 通过 ng-bind-html 插入到 DOM 中。

html( Jade )如下所示:

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

它基本上可以工作。但在包含的这个 html 中,我有一些透明的内容,例如我想要解析的 {{searchType}} 。不幸的是,事实并非如此,它在浏览器中显示“{{searchType}}”。我可以改变什么来使嵌入工作?

我阅读了有关 $compile$transclude 的内容,但我不知道如何使用它,也不知道它是否可以帮助我解决我的问题。谢谢!

最佳答案

在帕特里克的帮助下,我解决了这个问题。我将 Controller 更改为

 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 是根据传入的范围进行插值的。谢谢!

编辑: $interpolate 仅用于渲染 DOM 并通过范围解析它。它只是返回纯 html。如果您需要实际检索完整的工作 html 模板,其中包含 Angular 代码,请使用 $compile。我发现this answer对于解决 $interpolate$compile$parse 之间的差异非常有帮助。

关于javascript - Angular : using transclude with ng-bind-html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365352/

相关文章:

javascript - 使用 json 和 angularJs 访问范围内的嵌套菜单项

angularjs - $browser.cookies 不是一个函数

javascript - 两个不同文件中的 Angular 指令 : only one will appear in the view

html - Angular 指令泄漏子内容

javascript - 将 ES6 类构造函数赋值给 'this' 不重复变量名

javascript - 在javascript中删除一个字符串,不留空白?

javascript - AngularJs 与 Google map

AngularJS - 我可以根据三元运算符使用数据绑定(bind)值吗

javascript - AngularJS : Watch scope value of a injected service changed in one directive from another directive

javascript - 为什么像这段代码中那样将函数添加为对象属性时省略 () ?