szpic
szpic

Reputation: 4496

My directive is not firing

I want to recreate nsClick behavior with my directive ( changing priority). So this is my code:

angular.module('MyApp').directive('nsClickHack', function () {
return {
    restrict: 'E',
    priority: 100,
    replace: true,
    scope: {
        key: '=',
        value: '=',
        accept: "&"
    },
    link: function ($scope, $element, $attrs, $location) {
        $scope.method();
    }
}
});

and the line I'm trying to bind to:

<li ng-repeat="item in items" ns-click-hack="toggle(); item.action()">

toggle and item.action are from other directives.

Can you point me where I was making mistake?

Upvotes: 1

Views: 58

Answers (1)

New Dev
New Dev

Reputation: 49590

If you are trying to re-create ng-click, then it's probably better to look at the source of the ngClick directive.

For example, it does not create an isolate scope since only one isolate scope can be created on an element and it tries to be accommodating towards other directives. The alternative is to $parse the attribute value, which is what the built-in implementation is doing.

If you are just creating a "poor's man" version of ngClick, then, sure, you could use a callback function "&" defined on the scope, and invoke it when the element is clicked:

.directive("nsClickHack", function(){
  return {
    restrict: "A",
    scope: {
      clickCb: "&nsClickHack"
    },
    link: function(scope, element){
      element.on("click", function(e){
        scope.clickCb({$event: e}); // ngClick also passes the $event var
      });
    }
  }
});

The usage is as you seem to want it:

<li ng-repeat="item in items" ns-click-hack="toggle(); item.action()">

plunker

Upvotes: 2

Related Questions