简体   繁体   English

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

[英]how to register click event in directive in angularjs

Im new in angularjs.我是 angularjs 的新手。 I have a div #single I want to change the background color and then want to call back-end server on the click event.我有一个 div #single 我想更改背景颜色,然后想在点击事件上调用后端服务器。 I dont know how to this in angularjs custom directive .我不知道如何在 angularjs 自定义指令中做到这一点。 any help will b appreciated my html code任何帮助都会感谢我的 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 is directive that have following code . changColor 是具有以下代码的指令。 please help me how to do this请帮助我如何做到这一点

 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 
    }



    });
  });

You should use element.bind instead of element.on .您应该使用element.bind而不是element.on Target element can be accessed via event target or simply this.可以通过事件目标或简单地访问目标元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM