Render html with angular attributes from the angle controller

0

I'm currently trying to render an html from a method in the angle handler like this:

    me.func1 = function (codDep) {

    var str = '';

    angular.element(document.querySelector('#ligas')).remove();

    str += '<div id="ligas">';

    for (i = 0; i < me.Model.Ligas.length; i++) {
        var lig = me.Model.Ligas[i];
        str += '<a href="#" id="' + lig.Id + '" class="list-group-item" data-ng-click="me.func2()">' + lig.Nombre + '</a>';
    }

    str += '</div>';

    angular.element(document).find('#' + idElement).after(str);
};

The html is perfectly rendered up to data-ng of angulajs like this:
<a href="#" id="217" class="list-group-item" data-ng-click="me.func2()">Esto es un link</a> .

The problem I have is that when I click on the previously created element, it does not execute the data-ng-click="me.func2 ()" that contains the following method:

    me.func2 = function () {
    alert('Funcion #2 ejecutada');
};

I'm new to the framework, I really do not know if this is possible (it should not be another thing), or I'm doing something wrong.

Thank you in advance for the help you can give me.

    
asked by U. Angel 19.01.2017 в 18:40
source

2 answers

1

Angel how are you?

I think your problem is because you have to recompile the code you inject into HTML. The issue is that angular does not realize that you add attributes of angular programmatically unless you indicate it. To achieve this you have to use the $ compile service of angular. Inject the service and $ scope into your code and try the following:

 me.func1 = function (codDep) {

    var str = '';

    angular.element(document.querySelector('#ligas')).remove();

    str += '<div id="ligas">';

    for (i = 0; i < me.Model.Ligas.length; i++) {
        var lig = me.Model.Ligas[i];
        str += '<a href="#" id="' + lig.Id + '" class="list-group-item" data-ng-click="me.func2()">' + lig.Nombre + '</a>';
    }

    str += '</div>';

    angular.element(document).find('#' + idElement).after($compile(str)($scope));
};

Reference link $ compile

Finally, tell me how it went! Greetings!

    
answered by 16.10.2017 в 22:52
0

Look, try this in your code.

me.func1 = function (codDep) {

var str = '';

angular.element(document.querySelector('#ligas')).remove();

str += '<div id="ligas">';

for (i = 0; i < me.Model.Ligas.length; i++) {
    var lig = me.Model.Ligas[i];
    str += '<a href="#" id="' + lig.Id + '" class="list-group-item" ng-click="me.func2()">' + lig.Nombre + '</a>';
}

str += '</div>';

angular.element(document).find('#' + idElement).after(str);
};
    
answered by 19.01.2017 в 22:34