如何在angularjs中的指令中注册click事件

how to register click event in directive in angularjs

本文关键字:注册 click 事件 指令 angularjs      更新时间:2024-01-31

我在angularjs中是新的。我有一个div#single,我想更改背景颜色,然后在点击事件中调用后端服务器。我不知道如何在angularjs自定义指令中做到这一点。任何帮助都将不胜感激我的html代码

 <div id="single" class="" ng-style="{'background':x.is_read == 0 ?
 'rgba(98, 95, 95, 0.87)': '#A4A4A4'}"  ng-repeat="x in notification"  chang-color>

changColor是具有以下代码的指令。请帮我怎么做这个

 var app = angular.module('smac', []);
 app.controller('asd',function ($http,$scope) { 
 app.directive("changColor", function() {
 return {
        restrict: 'A',
         scope: {},
         link: link
    };
        function link (scope, element) {
        element.on('click', onClick);
    }
    function onClick () {
        alert('as');
        $(this).css({ 'background': '#A4A4A4' });
   // after this back end call 
    }

    });
  });

您应该使用element.bind而不是element.on。Target元素可以通过事件Target访问,也可以仅通过此访问。

var app = angular.module('smac', []);
app.controller('asd',function ($http,$scope) {  
  // this is controller body
});
app.directive("changColor", function() {
  return {
    restrict: 'A',
     scope: {},
     link: link
  };
  function link(scope, element) {
    element.bind('click', onClick);
  }
  function onClick (e) {
    alert('as');
    // Following lines as equal
    e.target.style.background = "#A4A4A4"; 
    this.style.background = "#A4A4A4"; 
    angular.element(this).css("background","#A4A4A4");
    // after this back end call 
  }
});