简体   繁体   中英

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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