AngularJS - accessing ng-click in custom directive

邮差的信 提交于 2020-01-10 02:30:07

问题


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.


回答1:


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");
    };



回答2:


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



来源:https://stackoverflow.com/questions/24363217/angularjs-accessing-ng-click-in-custom-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!