AngularJS - 在自定义指令中访问 ng-click [英] AngularJS - accessing ng-click in custom directive

查看:23
本文介绍了AngularJS - 在自定义指令中访问 ng-click的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解指令,我可以轻松地使用模板函数来丢弃我的 HTML,但是,如果我的模板中有一个 ng-click,我如何在链接函数中访问它?

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?

我的指令:

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

如您所见,我已将 $scope.scrollRight 添加到我的 link 函数中,但是单击时,控制台中没有任何显示.

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

如果我放置:

$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.

感谢任何帮助.

推荐答案

你的链接函数是这样定义的:

Your link function is defined like this:

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

然而你在 $scope 变量上编写函数:

however you are writing functions on $scope variable:

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

在这种情况下,$scope 实际上并没有注入到链接函数中(并且无法注入),因此链接只是带有参数的简单函数.您应该将 $scope 更改为 scope 并且它应该可以工作:

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

这篇关于AngularJS - 在自定义指令中访问 ng-click的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆