Haris
Haris

Reputation: 721

AngularJS ng-click not being fired from dynamic buttons in JQuery code

in jquery code I am trying to add a function in scope and then call that function from a dyncamically created button but ng-click is not being called:

$(document).on("click", ".inlinelbl", function () {
    var $this = $(this);
    var self = this;
    var localScope = angular.element(self).scope();

        if (localScope.InlineSave_Click == undefined) {
            localScope.InlineSave_Click = function (elem, event) {
               //function body
            }
        }

        if (localScope.InlineCancel_Click == undefined) {
            localScope.InlineCancel_Click = function (elem, event) {
                //function body
        }


    var html = "<span class='d'><button class='btn btn-default' ng-click='InlineSave_Click(this, event)' style='display:inline-block;'></button>";
    html += "<button class='btn btn-default' ng-click='InlineCancel_Click()'  style='display:inline-block;'></button></span>";

    var injector = angular.element(document.getElementById('app')).injector();
    var $compile = injector.get('$compile');
    var compiledHtml = $compile(html)(localScope);

    $this.closest("span.s-element").removeClass("hide");
    $this.closest("span.s-element").append($(compiledHtml[0].outerHTML));
}

});

Using chrome's extension for angularjs I have checked that localscope attached with the buttons has both the functions.

What am I missing here?

Thanks in anticipation!

Upvotes: 3

Views: 1441

Answers (1)

Anthony Chu
Anthony Chu

Reputation: 37520

Instead of taking the HTML from compiled output in this line,

$this.closest("span.s-element").append($(compiledHtml[0].outerHTML));

Append the compiled output as-is...

$this.closest("span.s-element").append(compiledHtml);

You may need to call localScope.$apply() afterwards.

Upvotes: 3

Related Questions