0

I have some htmltext in JS file which is again returning to html page. htmltext contain some circle svg element, which is showing properly when we are retrieve from API. On click of Circle I want to call one js function in same js file. Iwas trying with ng-click But Its not working

  htmlText += '<circle ng-click="getUrl()" cx="9.5" cy="9.5" stroke-width="2" stroke="'+statsObj[s].color+'" fill-opacity="0" r="8.00" title="" style="opacity: 1;" data-original-title="'+statsObj[s].state+'" ng-click="getUrl()"></circle>';

Is something is wrong in syntax or we can implement in other way ?? Thanks in Advance.

Bhagesh Arora
  • 547
  • 2
  • 12
  • 30

1 Answers1

0

This is because html string needs to be compiled if you need to use angular directives like ng-click. You can do this by creating a directive.

I've taken the directive from here and created a plunkr : call function inside $sce.trustAsHtml() string in Angular js

https://plnkr.co/edit/HZr2Bje2YBoY2luvB6zC?p=info for your reference.

    app.directive('compileTemplate', function($compile, $parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attr) {
      var parsed = $parse(attr.ngBindHtml);

      //Recompile if the template changes
      scope.$watch(
        function() { 
          return (parsed(scope) || '').toString(); 
        }, 
        function() {
            $compile(element, null, -9999)(scope);
        }
      );
    }
  };
});

You would want to use $sce.trustAsHtml as well to embed html in your main page.

Hope this helps!

p4ulinux
  • 329
  • 5
  • 14
  • Thanks, Its working but one new issue which I am facing is , when I am passing the parameter through function, for integer value its coming but in case of string I am getting undefined issue. see here.. ng-click="getUrl('+statsObj[s].count+','+statsObj[s].dag_id+')". from getUrl I am trying to pass to argument, count is coming fine but dag_id is not coming fine. Is something is wrong in syntax ?? – Bhagesh Arora Jul 10 '18 at 10:22
  • no need to enter '+ in the html string "getUrl(statsObj[s].count,statsObj[s].dag_id)" should work. updated plunkr : https://plnkr.co/edit/HZr2Bje2YBoY2luvB6zC?p=preview – p4ulinux Jul 10 '18 at 11:44
  • In that case, I am getting the error SyntaxError: Invalid or unexpected token........htmlText += '"; – Bhagesh Arora Jul 10 '18 at 12:05
  • not sure why, you have to create a plunkr and replicate the error, I've updated the plunkr with your svg circle and it works. Please see updated plunkr : https://plnkr.co/edit/HZr2Bje2YBoY2luvB6zC?p=preview – p4ulinux Jul 10 '18 at 12:25