AngularJS - accessing ng-click in custom directive

Oam Psy picture Oam Psy · Jun 23, 2014 · Viewed 22.1k times · Source

I'm trying to get my head around directives, i can easily use the template function to throw out my HTML, however, if i have an ng-click within my template, how can i access it within the link function?

My directive:

app.directive('directiveScroll', function () {
return {
      restrict: 'AE',
      replace: 'true',
      template:   '<div class="scroll-btns">' +
            '<div class="arrow-left" ng-click="scrollLeft(sectionID)"></div>' +
            '<div class="arrow-right" ng-click="scrollRight(sectionID)"></div>' +
        '</div>',
      link: function(scope, elem, attrs) {
        $scope.scrollRight  = function () {
          console.log("scrollRight  clicked");
        };
        $scope.scrollLeft  = function () {
          console.log("scrollLeft  clicked");
        };
      }
  };
});

As you can see, i have added $scope.scrollRight to my link function, however on click, nothing appears in the console.

If i place:

$scope.scrollRight  = function () {
     console.log("scrollRight  clicked");
};

$scope.scrollLeft  = function () {
     console.log("scrollLeft  clicked");
};

In my controller (and out of my directive), it works as expected.

Any help appreciated.

Answer

domakas picture domakas · Jun 23, 2014

Your link function is defined like this:

link: function(scope, elem, attrs) {..}

however you are writing functions on $scope variable:

    $scope.scrollRight  = function () {
      console.log("scrollRight  clicked");
    };
    $scope.scrollLeft  = function () {
      console.log("scrollLeft  clicked");
    };

In this case $scope is not actually injected into link function (and can't be injected), so link is just simple function with parameters. You should change $scope to scope and it should work:

    scope.scrollRight  = function () {
      console.log("scrollRight  clicked");
    };
    scope.scrollLeft  = function () {
      console.log("scrollLeft  clicked");
    };