【问题标题】:Creating Angular Element Once一次创建 Angular 元素
【发布时间】:2016-05-07 19:12:51
【问题描述】:

我有一个显示项目列表的角度页面。它遍历列表并将其显示在 div 中。这是它的 HTML 代码:

<div ng-repeat="item in items">
    <div class="item-title-section">
        <h1>{{item.text}}</h1>
    </div>
    <div class="item-special-section" 
            ng-show="item.type == 'FooB' ||
                    item.type == 'FooC' ||
                    item.type == 'FooD'">
        <div>
            <h2>Speical</h2>
            <p>Type Section</p>
        </div>
        <div>
            <span>{{item.text}}</span>
        </div>
    </div>
</div>

item-title-section 始终显示。但我只希望item-special-section 显示当前项目的类型是 B、C 还是 D。这里的问题是如果列表包含所有 3 个项目,我只希望 div 打印一次,但每个项目的文本打印。所以在这种情况下:

{
    {
        type: FooA,
        title: FooA,
        text: "Some text for this element"
    },
    {
        type: FooB,
        title: FooB,
        text: "Some text for this element"
    },
    {
        type: FooC,
        title: FooC,
        text: "Some text for this element"
    }
}

item-special-section div 打印两次。有没有一种角度静态创建html元素的方法,这意味着 if 它只创建一次?

【问题讨论】:

  • 什么是当前项目?

标签: javascript jquery css angularjs static


【解决方案1】:

因此,我为您的问题找到的一种解决方法是将仅显示一个特殊项目的逻辑分配给附加到 $scope 的单独函数。我创建了一个Plnkr Example 来帮助演示我的解释。

HTML

<div class="item-special-section"
     ng-show="showSpecialSection(item.type)">
  <p>I'm a special case!</p>
  <p>{{item.text}}</p>
</div>

在 HTML 中,我们只允许该元素显示 showSpecialSection 返回 true 并且我们传入 item.type

JavaScript

// Define out specialItems
$scope.specialItems   = ['FooB', 'FooC', 'FooE'];

// Create an array to stash the first item that fulfills
// the requirement in showSpecialSection
$scope.allowedItem    = [];

$scope.showSpecialSection = function(item) {
  // First we check if the item is in our defined list
  // of special items
  if ($scope.specialItems.indexOf(item) != -1) {

    // Next depending on if allowedItem has anything,
    // we either add it to allowedItem or check if it is
    // already inside allowedItem
    if ($scope.allowedItem.length == 0) {
      $scope.allowedItem.push(item);
      return true;
    }
    else if ($scope.allowedItem.indexOf(item) != -1) {
      return true;
    }
  }
  // return false if all other logic checks failed
  return false;
}

如果这对您有用,请告诉我,如果您有任何问题,请发表评论。干杯~

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 2021-06-08
    • 2020-11-11
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2019-01-07
    相关资源
    最近更新 更多