角指令链接功能使用内NG-点击VS绑定 [英] Using ng-click vs bind within link function of Angular Directive

查看:128
本文介绍了角指令链接功能使用内NG-点击VS绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在链接功能,有没有绑定到click事件的函数更多的角的方式?

In the link function, is there a more "Angular" way to bind a function to a click event?

现在,我在做...

myApp.directive('clickme', function() {   
  return function(scope, element, attrs) {
    scope.clickingCallback = function() {alert('clicked!')};
    element.bind('click', scope.clickingCallback);   
} });

这是做它的角方式还是一个丑陋的黑客?也许我不应该这样担心,但我是新来这个框架,并想知道做事情的正确的方式,特别是作为框架向前移动。

Is this the Angular way of doing it or is it an ugly hack? Perhaps I shouldn't be so concerned, but I'm new to this framework and would like to know the "correct" way of doing things, especially as the framework moves forward.

推荐答案

您可以在指令中使用控制器:

You may use a controller in directive:

angular.module('app', [])
  .directive('appClick', function(){
     return {
       restrict: 'A',
       scope: true,
       template: '<button ng-click="click()">Click me</button> Clicked {{clicked}} times',
       controller: function($scope, $element){
         $scope.clicked = 0;
         $scope.click = function(){
           $scope.clicked++
         }
       }
     }
   });

演示上plunkr

更多关于角指南指令。对我来说非常有帮助来自官方的角度博客文章关于这些指令的视频。

More about directives in Angular guide. And very helpfull for me was videos from official Angular blog post About those directives.

这篇关于角指令链接功能使用内NG-点击VS绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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