14

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.

Oam Psy
  • 8,555
  • 32
  • 93
  • 157

2 Answers2

17

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");
    };
domakas
  • 1,246
  • 8
  • 9
  • thats seems to have worked, and how do i access the sectionID i am passing on the ngClick in my scrollRight/Left function? – Oam Psy Jun 23 '14 at 10:20
  • `scope.scrollLeft = function (param) { console.log(param); };` this works the same as plain JS - passing params to functions corresponds to parameters in function declaration – domakas Jun 23 '14 at 10:23
0

Are you sure the link function parameter is named scope, not $scope?

Gildor
  • 2,484
  • 23
  • 35
  • @threed I know... Actually I meant the parameter name was different from what is used below in the code, if you take a closer look... And I believe it was the root cause. – Gildor Sep 01 '15 at 00:04