Angularjs:在指令中访问模板

时间:2014-11-18 04:28:32

标签: angularjs

我想要做的是将编译的模板附加到Angualrjs指令中的其他DOM元素。可能吗?怎么样?

我知道你可以使用transclude来包含模板并在标签中保留内容,但是如何将我编译的模板附加到其他DOM元素?

angular.module("my.directive")
.directive('passwordStrength', [function(){
    return {
        templateUrl: '/tpl/directive/passwordStrength.html',
        restrict: 'A',
        link: function postLink(scope, iElement, iAttrs){
            console.log('password strength is running');
            iElement.append($template) // problem here!!!


        }
    };
}]);

1 个答案:

答案 0 :(得分:1)

我不确定你要完成的是什么。您可能希望使用ng-include从URL中提取标记,而不是使用templateUrl属性,或者您可能希望在一个指令上使用templateUrl属性,然后再生成另一个指令并在第二个指令中包含该指令。我制作了一些示例指令来帮助您提供想法。

.directive('myDirective', function($compile) {
  return {
     scope: {
       path: '=myDirective'
     },
     link: function(scope, element) {
      // rather than use `templateUrl`, I'll get markup from the path using `ng-include`
      var html = '<div ng-include="path"></div>';
      // manipulate the markup however you want to
      html+= '<p>More stuff from "myDirective"!</p>';
      // append the markup
      element.append(html);
      // compile the markup so that Angular will know about it (or use the directive `compile` rather than `link`)
      $compile(element.contents())(scope);
    }
  };
})

// this is sort of like "extending" the other directive.
.directive('myOtherDirective', function() {
  return {
    scope: {
      path: '=myOtherDirective'
    },
    template: '<p>Stuff from "myOtherDirective"></div><div my-directive="path"></div>'
  };
})

Here's a demo you can mess around with.