Can the AngularJS directive template render a different directive?
I have a directive such that the template contains another directive:
var myModule = angular.module('mymodule', []);
myModule.directive('directive1', function() {
return {
restrict: 'E',
scope: {
config: '@'
},
template: '<div ng-controller="mycontroller", ng-init={{config}}><directive2 config={{config}}></directive2></div>'
}
}
The code is a little weird, and the purpose of directive1 is to act as a "wrapper" so it takes in the configuration and then passes it along with "mycontroller" and directive2.
I've tried this, but somehow mycontroller doesn't accept the configuration; He said config is undefined.
Just wondering if it is supported in Angular or is there a better way to do this?
Thank.
source to share
You can of course use nested directives.
But you have few errors in your directive template. Check out the example below and correct your template accordingly.
.directive('directive1', function() {
return {
restrict: 'E',
scope: {
config: '='
},
template: '<div>Config1:{{config}}<directive2 config="config"></directive2></div>',
link: function(scope) {
scope.config = {
test: 'from directive1'
};
}
}
})
.directive('directive2', function() {
return {
restrict: 'E',
scope: {
config: '='
},
template: '<div>config2: {{config}}</div>'
}
});
Finally, here is the plunker that shows the nested directives.
source to share
The problem is that you are creating a new controller using ng-controller="mycontroller"
a directive in the template.
ng-controller creates a new scope, so the config object does not exist in the scope of mycontroller. If you just uninstall it ng-controller="mycontroller"
, it will work.
source to share