首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角:使用transclude和ng-bind。

角:使用transclude和ng-bind。
EN

Stack Overflow用户
提问于 2014-12-08 19:25:38
回答 1查看 2.2K关注 0票数 2

我有以下设置:

代码语言:javascript
复制
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通过ng-bind-html插入到DOM中。

html (玉)如下所示:

代码语言:javascript
复制
#search(ng-controller="SearchController" search-directive)

基本上起作用了。但是在这个包含的html中,我有一些可转换的内容,比如我想要被解析的{{searchType}}。不幸的是,情况并非如此,它在浏览器中显示“{searchType}”。我能做些什么来让这个封闭性发挥作用呢?

我读过关于$compile$transclude的文章,但我不知道如何使用它,也不知道它是否能帮助我解决问题。太棒了!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-08 20:19:13

在帕特里克的帮助下,我解决了这个问题。我把控制器换成了

代码语言:javascript
复制
 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并通过作用域解析DOM。它只是返回普通的html。如果需要实际检索包含角代码的完整html模板,请使用$compile。我发现this answer在整理$interpolate$compile$parse之间的差异方面非常有帮助。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27365352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档