Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - accessing ng-click in custom directive

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.

like image 459
Oam Psy Avatar asked Jun 23 '14 10:06

Oam Psy


1 Answers

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");
    };
like image 179
domakas Avatar answered Nov 06 '22 07:11

domakas