Insert directive into the DOM using jqlite

2019-09-15 19:29发布

问题:

I need to use jqlite to insert the HTML for the directive, but for some reason the directive does not insert the template.

<div ng-app="docsSimpleDirective">
  <div ng-controller="Controller">
      <button ng-click="showCustomer($event)">click to see the customer</button>
  <div>
</div>

And my app.js looks like:

angular.module('docsSimpleDirective', [])
       .controller('Controller', ['$scope', function ($scope) {

          $scope.customer = {
             name: 'Naomi',
             address: '1600 Amphitheatre'
          };

          $scope.showCustomer = function($event) {
             angular.element($event.currentTarget).next().html("<div my-customer></div>");
          };
       }])
       .directive('myCustomer', function () {
          return {
          template: 'Name: {{customer.name}} Address: {{customer.address}}'
       };
});

http://jsfiddle.net/4nad43gn/

NOTE: This is just to try and recreate the situation i'm in, but the directive has to be inserted to the DOM in a similar way to the above - otherwise it will not work for my situation.

回答1:

As Michelem mention the best way to do DOM manipulation is using directive.

If you still want to do this by using controller you can take a look at my example: http://jsfiddle.net/4nad43gn/3/

$scope.showCustomer = function($event) {
   var element = document.querySelectorAll('[ng-controller=Controller] div');
   var tpl = $compile( "<div my-customer=''></div>" )( $scope );
   element[0].appendChild(tpl[0]);
};

You need to add $compile in your application. It's possible?



回答2:

Don't know why you did that but this is more simple:

JSFiddle

HTML:

<div ng-app="docsSimpleDirective">
    <div ng-controller="Controller">
        <button ng-click="showCustomer = true">click to see the customer</button>
        <div my-customer ng-show="showCustomer"></div>
    </div>
</div>

JS:

angular.module('docsSimpleDirective', [])
    .controller('Controller', ['$scope', function ($scope) {

    $scope.customer = {
        name: 'Naomi',
        address: '1600 Amphitheatre'
    };

    $scope.showCustomer = false;
}])
.directive('myCustomer', function () {
    return {
        template: 'Name: {{customer.name}} Address: {{customer.address}}'
    };
});

PS you can also use ng-ifinstead ng-show if you don't want to have the element (instead only hidden) before the click.