ng-controller not found (not working properly)

Asked

Viewed 37 times

0

I have a modal that has a "userCtrl" controller. I call all the scripts in the page loading (end of body), however, the modals, I load dynamically from the moment the user clicks the button, using the function $.get() I carry the modal and do 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, does not execute anything that is inside that controller in the modal, as if it was not found.

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

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

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

Stretch of modal

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

Excerpt from the controller

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 did this function that works for any modal.

  • There are several possibilities. Including a snippet of pertinent code can increase your chances of getting a reply that solves your problem.

  • I made some changes.

1 answer

0


After reading this link on github: https://github.com/angular/angular.js/issues/1307
The user ceymard quoted that

From what I understood in the end, the behavior of transclude is Perfectly normal in that it creates its creates a 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 about doing then was that every time I called a modal, I used $Compile sending $Scope to Response, done that, the code to open the modal looked 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 Sponse sending the $scope making it work properly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.