Search code examples
angularjszurb-foundationangularjs-ng-repeatangular-foundation

Conditionally apply hasDropdown directive on ng-repeated element


I'm working on a project where I use both angularJS and foundation, so I'm making use of the Angular Foundation project to get all the javascript parts of foundation working. I just upgraded from 0.2.2 to 0.3.1, causing a problem in the top bar directive.

Before, I could use a class has-dropdown to indicate a "top-bar" menu item that has a dropdown in it. Since the menu items are taken from a list and only some have an actual dropdown, I would use the following code:

<li ng-repeat="item in ctrl.items" class="{{item.subItems.length > 0 ? 'has-dropdown' : ''}}">

However, the latest version requires an attribute of has-dropdown instead of the class. I tried several solutions to include this attribute conditionally, but none seem to work:

<li ng-repeat="item in ctrl.items" has-dropdown="{{item.subItems.length > 0}}">

This gives me a true or false value, but in both cases the directive is actually active. Same goes for using ng-attr-has-dropdown.

this answer uses a method of conditionally applying one or the other element, one with and one without the directive attribute. That doesn't work if the same element is the one holding the ng-repeat so i can't think of any way to make that work for my code example.

this answer I do not understand. Is this applicable to me? If so, roughly how would this work? Due to the setup of the project I've written a couple of controllers and services so far but I have hardly any experience with custom directives so far.

So in short, is this possible, and how?


Solution

  • As per this answer, from Angular>=1.3 you can use ngAttr to achieve this (docs):

    If any expression in the interpolated string results in undefined, the attribute is removed and not added to the element.

    So, for example:

    <li ng-repeat="item in ctrl.items" ng-attr-has-dropdown="{{ item.subItems.length > 0 ? true : undefined }}">
    

    angular.module('app', []).controller('testCtrl', ['$scope',
      function ($scope) {
        $scope.ctrl = {
          items: [{
            subItems: [1,2,3,4], name: 'Item 1'
          },{
            subItems: [], name: 'Item 2'
          },{
            subItems: [1,2,3,4], name: 'Item 3'
          }]
        };
      }
    ]);
    <div ng-app="app">
      <ul ng-controller="testCtrl">
        <li ng-repeat="item in ctrl.items" ng-attr-has-dropdown="{{ item.subItems.length > 0 ? true : undefined }}">
          {{item.name}}
        </li>
      </ul>
    </div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>