1

I want to create a directive as a component, such that its not dependent on any controllers as such.

I have been trying to find out how to get a button click listener defined. But couldnt suceed yet.

angular.module('nestedDirectives', [])
.directive("parent", function () {
    function linker(scope, element, attribute, controllers) {
        console.log("linker called");
        element.on("click", function clicked(event) {
            console.log("clicked");
            console.dir(this);
            element.prepend("<h1>Hello</h1>");
        });
    }

    return {
        restrict: 'A',
        template: '<div><h5>An Item</h5><button ng-click="clicked()">Click Me</button></div>',
        link: linker,
        scope: {}
    }
})

In the template, no matter what i click the element.on("click") would get called. I want to call a clicked() method when button is clicked.

Here is the Plunker for the same.

1 Answer 1

1

The link function gets the scope (an isolated scope in your case) as the first argument, so you can do something like:

.directive("parent", function () {
  function linker(scope, element, attribute, controllers) {
    console.log("linker called");
    //add the "clicked" function to your scope so you can reference with ng-click="clicked" in your template
    scope.clicked = function() {
      console.log("clicked");
      console.dir(this);
      element.prepend("<h1>Hello</h1>");
    };
  }

  return {
    restrict: 'A',
    template: '<div><h5>An Item</h5><button ng-click="clicked()">Click Me</button></div>',
    link: linker,
    scope: {}
  };
});

Here is your updated plunkr http://plnkr.co/edit/7mlcSB4phPO5EdEQqTj0

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Using scope didn't strike me at all.

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.