0

I have an angularjs sample code snippet here where i can bind the html tags using ng-bind-html directive. But how can I include some other tags like angularjs ng-click, id tag etc inside ngBindHtml directive like

<a href="javascript:void(0);" id="myLink" ng-click="myFunct()">Test</a>

My sample code is here:

var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myText = "<a href='#' ng-click='someFunction()'>Test</a>";

    $scope.someFunction = function(){
    alert("Link Clicked");
    };
});

FYI, the data is loaded dynamically from server side script and i have to use ng-bind-html inside ng-repeat directive and i have to pass respective id's to click events something like ng-click="myFunction(x.id)" as in sample 2.

2
  • 1
    It seems like this could lead to hackers being able to run untrusted javascript/html on your site which would be a bad thing. You can include static content (or dynamic content from your server I suppose) via an ng-include... Commented Mar 29, 2016 at 4:35
  • mglison is correct, however if you are in control of the data being displayed and need to do this, for example as templating in a customer cell on a data table (the use case I have used this before). Then you need to Angular Compile the code. I'll take a look at the jsFiddle. Commented Mar 29, 2016 at 4:40

1 Answer 1

2

As suggested @Dr Jones, you need use $compile directive.

Live example on jsfiddle.

angular.module('ExampleApp', [])
  .controller('ExampleController', function($scope) {
    $scope.myText = "<button ng-click='someFunction(1)'>{{text}}</button>";
    $scope.text = "Test";
    $scope.someFunction = function(val) {
      console.log(val);
    };
  })
  .directive('bindHtmlCompile', function($compile) {
    return {
      restrict: "A",
      scope: {
        bindHtmlCompile: "="
      },
      link: function(scope, elem) {
        scope.$watch("bindHtmlCompile", function(newVal) {
          elem.html('');
          var newElem = angular.element(newVal);
          var compileNewElem = $compile(newElem)(scope.$parent);
          elem.append(compileNewElem);
        });
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">
    <h3>
  Write code for test button
  </h3>
    <textarea cols="100" ng-model="myText"></textarea>
    <div bind-html-compile="myText">

    </div>
  </div>
</div>

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

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.