如何以角度为元素添加内包装?

时间:2016-05-25 05:53:14

标签: javascript angularjs

我想要一个角度指向性来为DOM元素添加内部包装器。不幸的是,它不是包装而是替换元素的内部部分。 (see plunker

所以我有这个html片段:

<body ng-app="plunker">
  <div class="outer" wrapp-my-content>
    <label>Name: </label>
    <input type="text" ng-model="name" />
    <p>Hello {{name}}</p>
  </div>
</body>

该指令应将其更改为

<body ng-app="plunker">
  <div class="outer" wrapp-my-content>
      <div class="inner-wrapper">
        <label>Name: </label>
        <input type="text" ng-model="name" />
        <p>Hello {{name}}</p>
      </div>
  </div>
</body>

但我得到的是

<body ng-app="plunker">
  <div class="outer" wrapp-my-content>
      <div class="inner-wrapper">
      </div>
  </div>
</body>

指令代码:

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

app.directive('wrappMyContent', function() {
  return {
    restrict: 'A',
    transclude: true,
    replace: true,
    link: function(scope, element) {
      var innerWrapper = angular.element('<div class="inner-wrapper" ng-transclude></div>');
      element.prepend(innerWrapper);
    }
  }
});

我该如何解决?

2 个答案:

答案 0 :(得分:2)

您通过链接混合了ng-transclude和自定义转换:

<强> 1。使用template指令(demo):

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

//Recommended angular-way
app.directive('wrappMyContent', function() {
  return {
    restrict: 'A',
    transclude: true,
    template:'<div class="inner-wrapper" ng-transclude></div>',
    link: function(scope, element) {
    }
  }
});

<强> 2。通过自定义链接进行转换(demo):

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

//Equals transclude by your self
app.directive('wrappMyContent', function($compile) {
  return {
    restrict: 'A',
    scope:true,
    link: function(scope, element) {
      var innerContent = element.html();
      var innerWrapper = angular.element('<div class="inner-wrapper"></div>').append(innerContent);

      //Do compile work here.
      $compile(innerWrapper)(scope.$parent)
      element.empty().append(innerWrapper);

    }
  }
});

答案 1 :(得分:1)

'<div class="inner-wrapper" ng-transclude>'部分使用模板,而不是只创建一个元素并在其前面添加... ng-transclude指令不会被处理,除非它已经编译了模板将是