0

I have a directive that displays an icon with a little cross. When the user clicks on this cross, a callback should be called.

Here's the code of the directive template:

<div class="item" title="{{name}}">
  <button type="button" class="close">
    <span ng-click="onDelete()">&times;</span>
  </button>
  <span class="glyphicon glyphicon-folder-open"></span>
</div>

The Javascript of the directive:

angular.module('hiStack').directive('hsItem', function() {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'item.tpl.html',
    scope: {
      onDelete: '&',
      title: '@'
    }
  };
});

Finally, the code that uses the directive:

<hs-item on-delete="deleteGroupModal = true" title="TestTitle"></hs-item>

deleteGroupModal = true is never called when I click on the cross. If I pass a function instead like deleteGroup(), it works. How can I pass an assignment like we usually do with ng-click for example?

Thank you.

7
  • 1
    You have to create and pass function in which you will define: deleteGroupModal = true and it should work. It is not possible without declaring a function. & is used for it. Commented Aug 16, 2016 at 8:17
  • Isn't it possible to do like the ng-click directive like ng-click="test = true" ? Commented Aug 16, 2016 at 8:20
  • What do you mean by "like ng-model directive"? In ng-model you can only pass variable ($scope) without any condition. Commented Aug 16, 2016 at 8:21
  • Sorry, I made a mistake, I meant like the ng-click Commented Aug 16, 2016 at 8:22
  • Nope, it is not possible. & in directive expects only function. You can use @ if you need only a value if you need true or false and then create function inside your directive. Commented Aug 16, 2016 at 8:24

1 Answer 1

1

As Igor Janković said, it's better to pass a function than to write it directly on the attribute.

That said, it's possible to eval the expression passed on the attribute like this:

angular.module('hiStack').directive('hsItem', function() {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'item.tpl.html',
    scope: {
      title: '@'
    },
    link: function(scope, element, attrs) {
        scope.onDelete = function() {
            // Eval the code on the parent scope because directive's scope is isolated in this case
            if (attrs.onDelete) scope.$parent.$eval(attrs.onDelete);
        }
    }
  };
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.