I'm struggling to grasp the concept of inheriting a parent controller from a directive. In my setup, I have a simple example with a controller named MainCrtl
. This controller is responsible for creating and removing an array of directives called inner
. However, I am encountering an issue when trying to access the methods of MainCtrl
from my directives, resulting in an error in the browser console. Below is the code snippet:
app.js
angular
.module('myApp', ['ngRoute'])
.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'MainCtrl',
controllerAs: 'main'
});
});
scripts/controllers/main.js
angular.module('myApp')
.controller('MainCtrl', function () {
var self = this;
var index = 1;
this.inners = [];
this.init = function() {
self.addInner();
};
this.addInner = function(){
self.inners.push({
name: 'Inner ' + index
});
index++;
};
this.init();
});
views/main.html
<p>main</p>
<button type="button" ng-click="main.addInner()">Add Inner</button>
<inner ng-repeat="inner in main.inners" data="inner"></inner>
scripts/directives/inner.js
angular.module('myApp')
.directive('inner', function(){
return {
restrict: 'E',
templateUrl: 'inner.html',
require: ['^MainCtrl', 'inner'],
controllerAs: 'inner',
bindToController: true,
scope: {
data: '='
},
controller: function(){ ... },
link: function(scope, element, attrs, ctrls){ ... }
}
});
Here's the error message displayed in the browser console:
[$compile:ctreq] Controller 'MainCtrl', required by directive 'inner', can't be found!
A Plunker demo showcasing the issue can be found here. Your assistance would be greatly appreciated.