【问题标题】:Can an angular directive require its own controller?角度指令可以需要自己的控制器吗?
【发布时间】:2014-07-24 05:04:37
【问题描述】:

这是一个简单的问题,但我似乎找不到任何相关文档...

我试图找出一个角度指令是否既可以继承父控制器也可以继承它自己的。考虑以下示例:

简单的自我继承

app.directive('screen', function() {
  return {
    scope: true,
    controller: function() {
        this.doSomething = function() {

        };
    },
    link: function($scope, el, attrs, ctrl) {
        // ctrl now contains `doSomething`
    }
  }
});

从父级继承

app.directive('screen', function() {
  return {
    scope: true,
    controller: function() {
        this.doSomething = function() {

        };
    }
  }
});
app.directive('widget', function() {
  return {
    scope: true,
    require: '^screen',
    link: function($scope, el, attrs, ctrl) {
        // ctrl now contains `doSomething` -- inherited from the `screen` directive
    }
  }
});

甚至还有多重继承...

app.directive('screen', function() {
  return {
    scope: true,
    controller: function() {
        this.doSomething = function() {

        };
    }
  }
});
app.directive('widget', function() {
  return {
    scope: true,
    require: ['^screen','^anotherParent'],
    link: function($scope, el, attrs, ctrl) {
        // ctrl[0] now contains `doSomething` -- inherited from the `screen` directive
        // ctrl[1] now contains the controller inherited from `anotherParent`
    }
  }
});

我想不通的是如何让指令同时继承父控制器和它自己的控制器。像这样:

app.directive('screen', function() {
  return {
    scope: true,
    controller: function() {
        this.doSomething = function() {

        };
    }
  }
});
app.directive('widget', function() {
  return {
    scope: true,
    require: '^screen',
    controller: function($scope) {
       // isolated widget controller
    },
    link: function($scope, el, attrs, ctrl) {
        // I need the `screen` controller in ADDITION to the isolated widget controller accessible in the link
    }
  }
});

这是可能的/正确的形式(还是我不知道的某种反模式)?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    事实证明,这比我想象的要明显得多……经过反复试验表明,指令实际上也可以要求自身。

    继承父级+本地控制器的正确方法似乎是:

    app.directive('screen', function() {
      return {
        scope: true,
        controller: function() {
            this.doSomething = function() {
    
            };
        }
      }
    });
    app.directive('widget', function() {
      return {
        scope: true,
        require: ['^screen','widget'],
        controller: function($scope) {
           this.widgetDoSomething = function() {
           };
        },
        link: function($scope, el, attrs, ctrl) {
            // ctrl[0] contains the `screen` controller
            // ctrl[1] contains the local `widget` controller
        }
      }
    });
    

    【讨论】:

    • 这就是我现在正在这样做的方式......我的 SO 搜索希望揭示一种更“优雅”的方法。我想这就是它的完成方式=/
    • 很高兴你问了这个问题,我花了很长时间才弄清楚。
    • 为什么需要 ^ 来要求 screen 指令?
    猜你喜欢
    • 1970-01-01
    • 2013-03-15
    • 2015-01-29
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2016-08-06
    相关资源
    最近更新 更多