ng-controller is not found (does not work correctly)

0

I have a modal that has a controller "userCtrl". I call all the scripts in the page loading (end of the body), however, the modal, I load dynamically from the moment the user clicks the button, using the function $.get() I load the modal and make a $(#modal).modal('show') .

The problem is that the ng-controller that is contained in the modal that is loaded when the user clicks does not work, it is as if the controller does not work, it does not execute anything inside that controller in the modal, as if it does not was found.

  • Why can this occur?
  • Is there any way to fix this?
  • I wonder if this is because the controller script is loaded before the ng-controller element.

Function that loads the html of the modal where ng-controller is included

showModal = function(id, path) {
    $.get(path, response => {
        $(".modals").append(response);
        $(id).modal('show');
        $(id).on("hidden.bs.modal", () => {
            $(id).remove();
        });
    });
}

Modal strand

<div class="modal fade" id="mdCreateGrupos" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" ng-controller="gruposCtrl" ng-init="init()">

Controller Excerpt

app.controller("gruposCtrl", function($scope, $gruposService, $compile) {
$('#mdCreateGrupo').on('show.bs.modal', function (event) {
    $(".alert").remove();
    $("#textGrupo").val("");
});

$scope.init  = function() {
    console.log('inicio');
}

Everything was working correctly until I used the $ .get function, before I was using ng-include, but it was very verbose because it was an ng-include for each modal, now I've done that function that works for any modal.

    
asked by anonymous 08.03.2018 / 17:26

1 answer

0

After reading this issue in github: link
The user ceymard cited that

  From what I understood in the end, the behavior of transclude is perfectly normal in that it creates its new scope. So does ng-controller, which results in having them each have a distinct scope and thus not be able to interact together.

What I thought of doing then was that every time I call a modal, I used $ compile by sending the $ scope to the response, so the code to open the modal looks like this:

showModal = function(id, path) {
    $.get(path, response => {
        $(".modals").append($compile(response)($scope));
        $(id).modal('show');
        $(id).on("hidden.bs.modal", () => {
            $(id).remove();
        });
    });
}

That is, every time I call the modal, I compile the response by sending $scope making it work correctly.

    
08.03.2018 / 17:59