Show dynamic directives with AngularJS

0

I have the following problem:

It turns out that I want to show a <user></user> directive with Angular and load the policy code into it via a templateURL . But this directive has to be shown when you click on a button or div through a ng-click . I give you an example that I did to test if I could load it. The directive works well if I directly charge but do not do it dynamically.

The code HTML of the part where it would have to be loaded is:

<div ng-click="showTag()">Click me</div>
    <div id="loquesea">
    </div>  
</div>

And the Angular code that I generated is the following:

angular
  .module("plantillas_app",[])
  .controller("plantillas_ctrl",controlTemplates)
  .directive('usuario',templates);

function templates () {
    console.log("Cargando template...");
    return{
        restrict:'AE',
        templateUrl:'template1.html',
        scope:{
             idCliente:"=persona"
        }

    };
}

function controlTemplates ($scope,$http){                       
    $scope.usuario1= {nombre:"Juan",apellidos:'Perez Gomez',edad:'32'}
    $scope.usuario2= {nombre:"Pedro",apellidos:'Jimenez Gomez',edad:'33'}

    $scope.showTag = function () {
        console.log("Cargando contenido");
        $("#loquesea").html("<usuario persona='usuario1'></usuario><usuario persona='usuario2'></usuario>");
    }
}

Can someone tell me or explain why this is happening?

    
asked by Jose Vila 15.04.2016 в 13:10
source

1 answer

1

First of all, a controller should never directly access the template, precisely that's what the directives are for. It is not a good practice to insert HTML code directly from your controller.

What you want to do is simpler than that, you can use the directive ngIf , with it , you can show elements based on conditions, which in this case, could be a Boolean variable in your controller. So your code would look something like this:

<div ng-click="showTag()">Click me</div>
    <usuario persona="usuario" ng-if="mostrar"></usuario>
</div>

And your Javascript:

function controlTemplates ($scope,$http){
    $scope.mostrar = false;
    $scope.usuarios = {'usuario1': {nombre:"Juan",apellidos:'Perez Gomez',edad:'32'}, 'usuario2': {nombre:"Pedro",apellidos:'Jimenez Gomez',edad:'33'}};

    $scope.showTag = function () {
        $scope.usuario = $scope.usuarios.usuario1;
        $scope.mostrar = true;
    }

}

In this way, the first directive <usuario> would not appear, but when you click on the div it would. You can also see how using ngIf, the HTML content of the directive is not in your DOM when it is not showing, it is added automatically when the condition is fulfilled. On the contrary, there is the directive ngShow , which always loads the content in the DOM, and shows it or hidden using CSS.

I hope it serves you. Greetings!

    
answered by 15.04.2016 / 15:34
source