wyc
wyc

Reputation: 55273

How to test the existence of an attribute in a directive?

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?

Upvotes: 3

Views: 106

Answers (3)

fracz
fracz

Reputation: 21249

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.

Upvotes: 2

Gustav
Gustav

Reputation: 3576

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

Upvotes: 1

michelem
michelem

Reputation: 14590

Just add true:

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

JSFiddle

Upvotes: 1

Related Questions