Arthur Stepanyuk Arthur Stepanyuk - 1 month ago 6
AngularJS Question

Conditionally add attribute directive to the ng-repeat

I would like to know if its possible to add attribute directive to some elements inside of ng-repeat. I have tried checking CSS class or id but without luck.

Example code

class ItemNavigation {

constructor(NavigationService ) {
this.NavigationService = NavigationService;
}

}

angular.module('core')
.directive('itemNavigation', function ($timeout) {
return {
bindToController: true,
scope: {
itemId: '='
},
controllerAs: '$ctrl',
restrict: 'A',
link: function(scope, elem, attrs, ctrl) {
$timeout(() =>{
elem.bind('click', function() {
let noRedirect = $(this).hasClass('no-redirect');
// this approch doesnt work it never finds class
if(!noRedirect) return ctrl.NavigationService.goToItemDetails(ctrl.itemId)
})
})
;
},
controller: ItemNavigation
};
});


Example of html

<tr ng-repeat="item in $data track by item.id" item-navigation item-id="item.id">
<td class="no-redirect">I dont want my directive to work here</td>
<td>I want my directive to work here</td>
<td>I want my directive to work here</td>
<td class="no-redirect">I dont want my directive to work here</td>
<td>I want my directive to work here</td>
<td>I want my directive to work here</td>
</tr>


I would be grateful for any help

Answer

I think you can; As per my understanding, you want to put a condition for even rows only.

One easy solution: Put a condition using $index inside ng-repeat rows.

  <tr ng-repeat="item in $data track by item.id" item-navigation item-id="item.id">
  <td class="no-redirect" ng-if="$index % 3 == 0">I dont want my directive to work here</td>
  <td class="no-redirect" ng-if="$index % 2 == 0">I want my directive to work here</td>

</tr>

These are the changes you need to make in your directive.

   app.directive('rowNavigation', function ($timeout) {
    return {
      scope: {
    itemId: '='
  },
  controllerAs: 'ctrl',
  restrict: 'A',
  link: function(scope, elem, attrs, ctrl) {
      $timeout(function() {
      elem.bind('click', function() {
         console.log(ctrl)
         alert(ctrl.itemId);
      })
   });
  },
  controller: function($scope) {
    this.itemId = $scope.itemId
   } 
};
});

And in you ng-repeat, change it to

 <tr ng-repeat="one in data"  item-id="one.id"
  class="table table-striped table-bordered">
    <td  class="no-redirect">Dont alert when i click here</td>
    <td row-navigation item-id="one.id">Alert when i click here</td>
    <td row-navigation item-id="one.id">Alert when i click here</td>
  </tr>

Hope this helps.