3

I want to enable a button based on whether there's the atribute editable in the directive:

Editable:

  <table-list items="users" editable></table-list>

Non-editable:

  <table-list items="users"></table-list>

I tried this:

 .directive('tableList', function ($attr) {
    return {
      restrict: 'EA',
      template: '<a ng-if="editable" class="btn btn-default" href="#">Add to group</a>' +
    '<table class="table table-stripped">' +
    '<thead>' +
      '<tr>' +
        '<th>#</th>' +
        '<th>Name</th>' +
        '<th>Users</th>' +
        '<th>Buildings</th>' +
        '<th>Created at</th>' +
      '</tr>' +
    '</thead>' +
    '<tbody>' +
      '<tr ng-repeat="item in items">' +
        '<th scope="row"><input type="checkbox" value="0"></th>' +
        '<td><a href="#/groups/{{item.id}}">{{item.name}}</a></td>' +
        '<td>_</td>' +
        '<td>_</td>' +
        '<td>_</td>' +
      '</tr>' +
    '</tbody>' +
      '</table>',
      scope: {
    items: "=",
    editable: "="
      },

But the button isn't showing.

What's the proper way of doing this?

alexchenco
  • 53,565
  • 76
  • 241
  • 413
  • 1
    Possible duplicate of [Check existence of attribute in Angular Directive](http://stackoverflow.com/questions/25811734/check-existence-of-attribute-in-angular-directive) – fracz Jan 05 '16 at 08:47

3 Answers3

2

If you want to rely on a presence of the attribute only (even if it is set to false), you can check if it is defined with the $attrs in the link function:

scope: {
  items: "="
},
link: function($scope, $element, $attrs) {
  $scope.editable = $attrs.editable !== undefined;
}

JSFiddle.

However, this will not be reactive (i.e. if you add the attribute in runtime, directive won't show the button). You might use $attrs.$observe() if you need it.

Community
  • 1
  • 1
fracz
  • 20,536
  • 18
  • 103
  • 149
1

Just add true:

<table-list items="users" editable="true"></table-list>

JSFiddle

michelem
  • 14,430
  • 5
  • 50
  • 66
1

When getting an attribute and setting it to the scope like that you're setting the value. And your editable-attribute has no value. If you'd do <table-list items="users" editable="true"></table-list> it would work better.

And in the directive you could probably use @ instead of = for the attribute.

This will set the editable property on the scope to the string "true", if you want it to be a boolean you might need some logic in the link function

Gustav
  • 3,408
  • 4
  • 24
  • 41