使用指令装饰HTML元素

时间:2014-01-28 16:53:12

标签: angularjs angularjs-directive

我正在调用返回HTML的API,其中包含一些code标记。

我期待用指令装饰该元素,但由于HTML来自API,我无法添加指令属性。

Angular用指令装饰form等元素,所以我做了类似的事情:

angular.module('myApp')
.directive('code', function($log) {

  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      $log.info('Code Directive');
    }
  };

});

虽然控制台日志没有打印。我错过了什么吗?

编辑:我注意到该日志适用于在API调用之前创建的code个元素。但是,当API将代码注入到html中时,该指令不会运行。有没有办法手动让它运行?

2 个答案:

答案 0 :(得分:2)

您需要使用$compile service编译您的html:

$http.get('path/to/template')
  .then(function(response){
    $scope.html = $compile(response.data)($scope);
  })

答案 1 :(得分:0)

如果您的代码来自API,它可能会在Angular编译后添加到您的页面中 - 这意味着该指令未连接到页面中。

为了使它工作,你应该在插入后编译你的新html。请参阅:Compiling dynamic HTML strings from database,特别是答案:https://stackoverflow.com/a/18157958/149060

其中:

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

app.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});

function MyController($scope) {
  $scope.click = function(arg) {
    alert('Clicked ' + arg);
  }
  $scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}