Custom Angular directive to show or hide items in multiple views

2

I am working with Angular js in a modular application. When a user enters the application, it determines the number of boats that the company has and in the menu view it shows a selector that allows to select one of the boats to manage it.

<ul class="dropdown-menu animated fadeIn m-t-xs">
  <li>
    <a ng-click="changeBoat(boatInfo)" class="ng-binding">
      182 /  ASTROBOAT
    </a>
  </li>
  <li>
    <a ng-click="changeBoat(boatInfo)" class="ng-binding">
      180 /  START BOAT
    </a>
  </li>
  <li>
    <a ng-click="changeBoat(boatInfo)" class="ng-binding">
      178 /  STORM BOAT
    </a>
  </li>
</ul>

Also in the dashboard module that appears on the same screen, the application displays a table with the information of all the boats. The point is, when the company only has one boat, it does not make sense to show the selector or the board. I want to use other components in those cases. I'm thinking of creating a user-if-single-boat directive, which allows you to show or hide components in all views, something like this:

<ul class="dropdown-menu animated fadeIn m-t-xs" user-if-single-boat> ...
<table class="..." user-if-single-boat> ...

I also know that I could do it with a ng-if that validates a variable in the $rootScope ( <ul class="dropdown-menu animated fadeIn m-t-xs" ng-if='isMultiBoats'> ), but I do not want to use the $rootScope itself, taking into account that the validation of that attribute must be do throughout all the modules of the application. What other alternative do I have for it, or what should this directive be like?

    
asked by AndreFontaine 26.09.2016 в 19:10
source

1 answer

1

The directive that you should create would inject a template, the one of the ul: <ul class="dropdown-menu animated fadeIn m-t-xs"> and when you use the directive you would add a ng-if or a ng-show or ng-hide according to what you want.

Your directive would be declared like this:

angular.module('tumodulo')
.directive('tuNombreDeDirectiva', function() {
  return {
    templateUrl: 'templates/sets-panel.tmpl.html', // aquí iría tu ul
    controller: 'tuController', // si tienes un controlador con funcionalidad aquí va, sino, borras linea
    replace: true
  };
})

So then to inject that directive into your html and also condition it to show or not it could be:

<ul data-tu-nombre-de-directiva data-ng-show="isShowed"></ul>
    
answered by 12.10.2016 в 00:51