如何使指令替换DIV中的所有内容,包括DIV本身?

时间:2013-12-09 08:00:32

标签: angularjs

我正在使用以下指令调用:

<div data-my-activity></div>

这是指令:

app.directive('myActivity', function () {
    return {
        restrict: "A",
        template: "<div class='activity-mask' data-ng-show='fetching.length > 0' >" +
        "<ul>" +
        "<li data-ng-repeat='activity in fetching'>{{ activity }}</li>" +
        "</ul>" +
        "</div>" +
        "<div class='activity-mask' data-ng-show='loading.length > 0' >" +
        "<ul>" +
        "<li data-ng-repeat='activity in loading'>{{ activity }}</li>" +
        "</ul>" +
        "</div>"
    };
});

当我使用这个指令时,它给了我:

<div data-my-activity="">
   <div class="activity-mask ng-hide" 
        data-ng-show="fetching.length &gt; 0">
      <ul><!-- ngRepeat: activity in fetching --></ul>
   </div>
   <div class="activity-mask ng-hide" 
        data-ng-show="loading.length &gt; 0">
      <ul><!-- ngRepeat: activity in loading --></ul>
   </div>
</div>

如果fetching.length和loading.length都等于0,有没有办法可以让我得到以下内容?

<div style="display:none">
   <div class="activity-mask ng-hide" 
        data-ng-show="fetching.length &gt; 0">
      <ul><!-- ngRepeat: activity in fetching --></ul>
   </div>
   <div class="activity-mask ng-hide" 
        data-ng-show="loading.length &gt; 0">
      <ul><!-- ngRepeat: activity in loading --></ul>
   </div>
</div>

以及如果fetching.length或loading.length不等于0?

<div style="display:block">>
   <div class="activity-mask ng-hide" 
        data-ng-show="fetching.length &gt; 0">
      <ul><!-- ngRepeat: activity in fetching --></ul>
   </div>
   <div class="activity-mask ng-hide" 
        data-ng-show="loading.length &gt; 0">
      <ul><!-- ngRepeat: activity in loading --></ul>
   </div>
</div>

更新

我尝试了建议的答案,但它给出了引号的问题,因为我在一行上有三个级别的引号。

app.directive('myActivity', function () {
    return {
        restrict: "A",
        replace: true,
        template: "<div ng-style="{display: loading.length > 0 || fetching.length > 0 ? 'block' : 'none'}">
        "<ul>" +
        "<li data-ng-repeat='activity in fetching'>{{ activity }}</li>" +
        "</ul>" +
        "</div>" +
        "<div class='activity-mask' data-ng-show='loading.length > 0' >" +
        "<ul>" +
        "<li data-ng-repeat='activity in loading'>{{ activity }}</li>" +
        "</ul>" +
        "</div>" +
        "</div>"
    };
});

1 个答案:

答案 0 :(得分:4)

您应该可以通过选项

replace: true

进入指令,并且指定的模板将替换元素的所有html,包括元素本身

app.directive('myActivity', function () {
  return {
    restrict: "A",
    replace: true,
    template: "..."
  };
});

编辑:要动态显示/隐藏内容,您应该可以使用ngStyle设置display:none模板

template: '<div ng-style="{display: loading.length > 0 || fetching.length > 0 ? 'block' : 'none'}">....';

或者,你可以做一个ng,如果你实际上不需要DOM中的元素

template: '<div ng-if="loading.length > 0 || fetching.length > 0">....';

编辑:我有ngShow我实际上是指ngIf