不能从自定义指令 return/render html

Can't return/render html from a custom directive

我对 angular 的指令很陌生,并试图实现一个简单的指令来呈现动态 html。 考虑以下 html

<body ng-app="myApp" ng-controller="myCtrl">
    <my-directive></my-directive>
</body>

我想实现的是

的结果
<span>My HTML<span> 

风格:

span {
  color:blue;
}

我的指令:

myApp.directive("myDirective", ['$sce', function($sce) {
  return {
    restrict: "E",
    scope: {
      text: "="
    },
    template: '{{test}}',
    replace: true,
    transclude: false,
    link: function(scope, element, attrs) {
        scope.test  = "<span>My HTML<span>";
    }
  }
}]);

我所有的尝试都失败了,这是我的 codepen example,希望你能帮助我,因为我觉得我错过了什么。 顺便说一句,我相信这是因为它是 HTML,所以我尝试使用 $sce,但仍然没有成功。

已编辑:我为 span 标签添加了 css 样式,所以一旦它起作用,文本的颜色应该是蓝色。

通常,您不会将变量绑定到指令的范围,而是绑定到控制器的范围。尽量避免使用 $scope,因为这是最佳做法。

您的 index.html 看起来像:

<body ng-app="myApp">
    <my-directive></my-directive>
</body>

您的控制器:

myApp.controller("myCtrl", function() {
  var vm = this;
  vm.test = "Test";
});

最后,您的指令:

myApp.directive("myDirective", ['$sce', function($sce) {
  return {
    restrict: "E",
    template: '<span>{{vm.test}}</span>',
    replace: true,
    controller: "myCtrl",
    controllerAs: "vm"
  }
}]);

注意,您的变量 "test" 直接绑定到控制器。该控制器在您的指令中由 "controller" 和 "controllerAs" 引用。

如果对你有帮助,请告诉我。

编辑: 如果你想在 link 方法中分配变量值,你可以尝试:

myApp.directive("myDirective", ['$sce', function($sce) {
  return {
    restrict: "E",
    scope: {
      text: "@"
    },
    replace: true,
    transclude: true,
    template: '<span ng-bind="text"></span>',
    link: function(scope, element, attrs){
        scope.text = "<span>...</span>";
    }
  }
}]);

几件事:

  • scope.text:“=”仅适用于从 html 元素
  • 中获取文本属性的情况
  • 如果您在指令中分配它,请改用“@”
  • 在范围内定义的变量在模板内时仅由变量名引用
  • 指令在模板中始终需要一个根元素
  • 您可以使用 ng-bind 或 ng-bind-html(与您的 $sceProvider)将您的动态 html 绑定到根元素