AngularJs指令在单击时调用链接函数

时间:2016-09-08 12:18:36

标签: javascript html angularjs

我想知道如何指定何时应该调用指令的链接函数。

目前我有以下代码:



<my-directive username="abc"></my-directive>
&#13;
&#13;
&#13;

&#13;
&#13;
module.directive("myDirective", [{
  restrict: "A",
  link($scope, element, others) {
    //if element.clicked() {
    //  console.log("you clicked me");
    //}
  }
}]);
&#13;
&#13;
&#13;

正如你所看到的,我已经注释了我想要做的伪代码,并且我已经看到它可以做像element.onClick = function(){}这样的事情。但是当单击该元素时,似乎仍然没有调用它。

由于

3 个答案:

答案 0 :(得分:2)

试试这个:

element.on('click', function() {});

Angular使用内置jQuery Lite,因此您可以使用此功能。

答案 1 :(得分:0)

试试这个

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.abc = 'abc';
    
});



app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      username: '='
    },
    link:link,
    template: '<div>Click Here</div>'
  };
  function link(scope,elem,others){
    
     elem.bind('click', function() {
      console.log('on click');
    });  
    
  }
});
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js" data-require="angular.js@1.4.x"></script>
    <script src="app.js"></script>
  </head>

   <body ng-app="plunker" ng-controller="MainCtrl">
  <my-directive username="abc"></my-directive>
  </body>

答案 2 :(得分:0)

你也可以这样试试!

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.abc = 'abc';
    
});



app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      username: '='
    },
    link:link,
    template: '<div ng-click="click()">Click Here</div>'
  };
  function link(scope,elem,others){
    
   scope.click = function() {
        console.log('on click', scope.username);       
   }
  }
});
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js" data-require="angular.js@1.4.x"></script>
    <script src="app.js"></script>
  </head>

   <body ng-app="plunker" ng-controller="MainCtrl">
  <my-directive username="abc"></my-directive>
  </body>