角度指令是否需要自己的控制器?

时间:2014-07-24 05:04:37

标签: javascript angularjs

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

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

自我简单继承

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
    }
  }
});

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

1 个答案:

答案 0 :(得分:36)

事实证明,这比我想象的要明显得多......一点点的试验和错误表明指令实际上也需要自己。

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

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
    }
  }
});