AngularJS - accessing ng-click in custom directive
Asked Answered
W

2

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.

Waldrup answered 23/6, 2014 at 10:4 Comment(1)
@proxygear: It is not a typo. It is a lack of understanding on the users part at the time.Colum
D
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");
    };
Durarte answered 23/6, 2014 at 10:10 Comment(2)
thats seems to have worked, and how do i access the sectionID i am passing on the ngClick in my scrollRight/Left function?Waldrup
scope.scrollLeft = function (param) { console.log(param); }; this works the same as plain JS - passing params to functions corresponds to parameters in function declarationDurarte
I
0

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

Ithaman answered 23/6, 2014 at 10:10 Comment(1)
@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.Ithaman

© 2022 - 2024 — McMap. All rights reserved.