加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS – 动态创建的指令“require”无法正常工作

发布时间:2020-12-17 07:08:34 所属栏目:安全 来源:网络整理
导读:如果指令是动态创建的,则“require”选项不起作用,因此它不能引用其父项的控制器.我怎样才能使它工作? app.directive('parent',function ($compile) { return { controller: function() {},link: function (scope,el,attrs) { // "child" is dynamically cr
如果指令是动态创建的,则“require”选项不起作用,因此它不能引用其父项的控制器.我怎样才能使它工作?

app.directive('parent',function ($compile) {
  return {
    controller: function() {},link: function (scope,el,attrs) {
      // "child" is dynamically created
      el.append( $compile('<div child>')(scope) );
    }
  }
})

.directive('child',function () {
  return {
    require: "?^parent",link: function(scope,attrs,pCtrl) {
      // "child" cannot find its parent controller
      console.log("pCtrl is undefined: ",pCtrl);
    }
  }
})

这是一个plunker DEMO

解决方法

你需要在编译之前将子元素添加到父元素.

当指令编译时,它试图获取其父元素.从父元素,它试图找到父控制器.但是,在将其元素附加到其父元素之前,您正在编译子指令.

我为你创造了一个plnkr.结帐this

app.directive('parent1',function($compile,$timeout) {
  return {
    controller: function() {
      this.name = 'parent controller 1';
    },attrs) {
      // "child1" is dynamically created
     var elmChild = angular.element('<div child1>');
      el.append(elmChild);
      $compile(elmChild)(scope);
    }
  }
})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读