0

Am trying to add ng-click dynamically I know how it can be done in Jquery but don't know how I would do this in AngularJs. My code plots series of dots on a canvas and I want each dot to be clickable, am not sure how this can be done in Angular.

AngularJS Code:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

$scope.data = [
          [21,50],
          [30,150],
          [45,75],
          [98,121],
          [67,78],
          [35,80]
       ];

$scope.addData = function() {
     for(i=0; i<$scope.data.length; i++){    
        context.beginPath();
        context.arc($scope.data[i][0], $scope.data[i][1], 10, 0, 2*Math.PI);
        context.fillStyle = "#ccddff";
        context.fill();
        context.lineWidth = 1;
        context.strokeStyle = "#666666";
        context.stroke(); 
      }    
  }

HTML code:

<canvas id="canvas" style="border: 1px gray solid; float: left;> width:500px; height:500px;"></canvas>
1
  • You are trying to add click event on a canvas arc object? If that's the case then, you can write the ng-click event on the canvas DOM element and because the canvas is static element, it should not be difficult to do this. See this for further details: stackoverflow.com/questions/19133825/… Commented Dec 18, 2015 at 10:33

2 Answers 2

1

I think you shouldn't generate view parts from AngularJS controller. You should only generate data, which could be included in your HTML by for example ng-repeat directive, and then create a custom directive to process data.

Generated HTML could be like that:

<my-graph>
  <my-plot ng-repeat="MyPlotCollectionInMyController" />
</my-graph>

Then create a custom directive to process "my-plot" or "my-graph" elements. Official documentation.

Very good explanation and examples here.

The principle of a custom directive is to process attributes or in your case HTML elements, to change something : you could enumerate their children, completely replace the element "my-graph" with completely different HTML.

It is not so easy to create a custom directive. And as soon as you want to include a "ng-click", which is another directive, you must manage priorities accordingly : the "ng-click" directive have to be executed after your custom directive.

Sign up to request clarification or add additional context in comments.

Comments

0

not sure if you reasoning is right BUT anyway ... I believe you want to use the $compile service

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.