javascript - Angular 在使用 `ng-if` 时避免代码重复

标签 javascript angularjs

我当前的实现:

<div class="outer-class" ng-repeat="item in items">
  <div class="inner-class" ng-if="isShow">
    <div class="inner-class-1">{{item}}</div>
  </div>
  <div ng-if="!isShow" class="inner-class-1">{{item}}</div>
</div>

上面的代码可以运行,但是有很多代码重复:

  1. ng-if有两次吗(不能使用ng-switch,因为中间引入了新元素)
  2. <div ng-if="!isShow" class="inner-class-1">{{item}}</div>重复两次,只是因为我不希望元素( <div class="inner-class"></div> )封装我的数据,当 ng-if计算结果为假。

我想知道是否有更好的方法来重写它。

最佳答案

在这种情况下,您最好创建一个可以有条件地包装内容的自定义指令。你可以这样做:

angular.module('demo', []).controller('DemoController', function($scope) {
  $scope.items = [1, 2, 3];
  $scope.isShow = false;
})

.directive('wrapIf', function() {
  return {
    restrict: 'A',
    transclude: true,
    link: function(scope, element, attrs, controller, transclude) {

      var previousContent;

      scope.$watch(attrs.wrapIf, function(newVal) {
        if (newVal) {
          previousContent.parent().append(element);
          element.empty().append(previousContent);
        } else {
          transclude(function(clone, scope) {
            previousContent = clone;
            element.replaceWith(clone);
          });
        }
      })
    }
  };
});
.inner-class, .inner-class-1 {
  padding: 6px;
  background: #DDD;
}
.inner-class-1 {
  background: #34dac3;
}
.outer-class {
  margin-bottom: 6px;
}
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>

<div ng-app="demo" ng-controller="DemoController">

  <p>
    <button ng-click="isShow = !isShow">Toggle isShow ({{ isShow }})</button>
  </p>

  <div class="outer-class" ng-repeat="item in items">
    <div class="inner-class" wrap-if="isShow">
      <div class="inner-class-1" ng-click="test(item)">{{item}}</div>
    </div>
  </div>

</div>

关于javascript - Angular 在使用 `ng-if` 时避免代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34631233/

相关文章:

javascript - 基于路由参数动态注入(inject)特定工厂由于某种原因失败

javascript - 代码在数据到达之前进入函数 - 如何使其在继续之前等待所有数据?

angularjs - 将闭包编译器与 AngularJS 一起使用

javascript - 刷新后保留数据AngularJS

javascript - 如何在 HTTP 请求正文中 POST 这个 -d

javascript - json 未按正确顺序打印

javascript - 如何使用 window.open() 下载文件

javascript - 剂量值未正确通过验证

javascript - 根据按钮 ID 显示/隐藏表单

javascript - SVG 图层图像不会在 Mobile Safari 中以纵向模式显示