0

Here I created sample angular program for button click. but its not firing may i know where i did mistake? can any one help me on this.. thanks

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope, $sce) {
    $scope.buttonHtml = $sce.trustAsHtml("<button ng-click='showMessage(\"foo\")'>click me</button>");
    $scope.showMessage = function(message) {
        alert(message);
    }
    
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
    <div ng-bind-html="buttonHtml"></div>
</div>

1
  • you paste html that not compiled angular, that's why ng-click attribute not work Commented Jan 28, 2016 at 9:03

2 Answers 2

2

The problem is that even though the html renders nicely, Angular hasn't actually bound the ng-click to the scope, to do this you have to $compile it first.

var compiledHtml = $compile("<button ng-click='showMessage(\"foo\")'>click me</button>")($scope);
Sign up to request clarification or add additional context in comments.

1 Comment

While using $compile is the correct approach, $compile returns a link function which after applying on the relevant scope returns DOM elements (and not strings).
0

You will need to compile & link the element with the correct scope and replace the "old element". This should be done with a directive:

HTML:

<div ng-app="myApp" ng-controller="MyCtrl">
  <div replace-with-compiled-html="buttonHtml"></div>
</div>

JS:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
  $scope.buttonHtml = "<button ng-click='showMessage(\"foo\")'>click me</button>";

  $scope.showMessage = function(message) {
    alert(message);
  }
});

myApp.directive('replaceWithCompiledHtml', function($compile) {
  return {
    compile: function compile(tElement, tAttrs, transclude) {
      return {
        post: function preLink(scope, elem, iAttrs, controller) {
          // use the inherited scope -> get the wanted property via the attributes
          var scopePropName = iAttrs['replaceWithCompiledHtml'];

          // compile the html
          var linkingFunc = $compile(scope[scopePropName]);

          // link it with the correct inherited scope
          linkingFunc(scope, function(newElem) {
            // replace the new compiled element with the previous one
            elem.replaceWith(newElem);
          });
        }
      };
    }
  }
});

JSFIDDLE.

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.