2

Im new in 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. I dont know how to this in angularjs custom directive . any help will b appreciated my html code

 <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 . 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 } }); }); 
5
  • The directive is creating an isolate scope which isolates the notification variable in the ng-repeat. Also the style changes in the custom directive compete with the ng-style directive. Commented Apr 6, 2016 at 10:07
  • you are saying I have already implementing ng-class and repeat directive on this so i cant do apply further directive ? @georgeawg Commented Apr 6, 2016 at 13:16
  • You can combine directives on the same element but you need to avoid having the scopes conflict. See AngularJS Comprehensive Directive API -- scope. Commented Apr 6, 2016 at 13:31
  • so can you help me in registering a click event.. Commented Apr 6, 2016 at 14:22
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example.. Commented Apr 6, 2016 at 14:49

1 Answer 1

1

You should use element.bind instead of 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 } }); 
Sign up to request clarification or add additional context in comments.

3 Comments

Please see my updated code. Your directive is defined inside a controller. It should be defined outside as a separate angular component.
For the proof of directive's work check plnkr.co/edit/UwFfrpQc0py1RA7q90id
perhaps there may problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.