简体   繁体   English

使用ng-if时,角度避免代码重复

[英]Angular avoid code duplication when using `ng-if`

My current implementation: 我当前的实现:

<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>

The above code works, but there is a lot of code repetition: 上面的代码有效,但是有很多代码重复:

  1. ng-if is there twice ( ng-switch cannot be used since a new element is introduced in between) ng-if是否存在两次(无法使用ng-switch因为在两者之间引入了新元素)
  2. <div ng-if="!isShow" class="inner-class-1">{{item}}</div> is repeated twice, just because I do not want the element ( <div class="inner-class"></div> ) to encapsulate my data, when the ng-if evaluates to false. <div ng-if="!isShow" class="inner-class-1">{{item}}</div>重复了两次,只是因为我不想使用该元素( <div class="inner-class"></div> ),以在ng-if评估为false时封装我的数据。

I was wondering maybe if there is a better way to re-write the same. 我想知道是否有更好的方法可以重写相同的内容。

Maybe something like this? 也许是这样的吗?

 //optional wrapper function resolveTemplate(tElement, tAttrs) { if (tAttrs.showWrapper){ return "<div ng-class='wrapperClass' ng-transclude></div>" } else return "<ng-transclude></ng-transclude>"; } app.directive('optionalWrapper', function() { return { restrict: 'E', transclude: true, template: resolveTemplate, link: function($scope, el, attrs) { $scope.wrapperClass = attrs.wrapperClass; } }; }); 

To be used like this: 要这样使用:

 <optional-wrapper wrapper-class='inner-class-1' show-wrapper='isShow'></optional-wrapper> 

In this case you would better off creating a custom directive that could conditionally wrap contents. 在这种情况下,最好创建一个可以有条件包装内容的自定义指令。 You could do something like this: 您可以执行以下操作:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM