使用 jqlite 将指令插入 DOM [英] Insert directive into the DOM using jqlite

查看:21
本文介绍了使用 jqlite 将指令插入 DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 jqlite 为指令插入 HTML,但由于某种原因指令没有插入模板.

<div ng-controller="控制器"><button ng-click="showCustomer($event)">点击查看客户</button><div>

我的 app.js 看起来像:

angular.module('docsSimpleDirective', []).controller('Controller', ['$scope', function ($scope) {$scope.customer = {name: '内奥米',地址:'1600 圆形剧场'};$scope.showCustomer = 函数($event){angular.element($event.currentTarget).next().html("<div my-customer></div>");};}]).directive('myCustomer', function () {返回 {模板:'姓名:{{customer.name}} 地址:{{customer.address}}'};});

http://jsfiddle.net/4nad43gn/

注意:这只是为了尝试重新创建我所处的情况,但必须以与上述类似的方式将指令插入到 DOM 中 - 否则它将不适用于我的情况.

解决方案

正如 Michelem 提到的,进行 DOM 操作的最佳方式是使用指令.

如果你仍然想通过使用控制器来做到这一点,你可以看看我的例子: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]);};

您需要在应用程序中添加 $compile.有可能吗?

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.

解决方案

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?

这篇关于使用 jqlite 将指令插入 DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆