Reputation: 1059
My web application has several pages who have their own controller. Inside these pages I use directives who also have a controller. All controllers use the controllerAs syntax and they are all set as vm
. According to this article this should work. However, I'm having trouble making it work in combination with a directive. In this codepen I have reproduced a similar situation:
http://codepen.io/csteur/pen/LGEdLy
In this example the parent scope is also broken because of the nested directive. Can anyone explain why this happens or how this can be changed to make it work?
Upvotes: 4
Views: 95
Reputation: 13258
When you define var vm = this;
inside nestedDirectiveController
, the scope of vm
is limited to nestedDirectiveController
only.
Since you directive has isolated scope and your template uses this nestedDirectiveController
function to evaluate the expression, it gets title value null
and we see no title.
If you want shared scope then you can provide scope : true
config in your directive. So that the directive gets its own scope that inherits prototypically from the parent scope.
angular
.module('app')
.directive('nestedDirective', function() {
return {
restrict: 'E',
scope: true,
controller: 'nestedDirectiveController',
controllerAs: 'vm',
template:'<div> {{vm.message}} </div>'
};
});
Upvotes: 0
Reputation: 3717
You need to isolat your contoller with the directory
angular.module('app', []);
angular.module('app').controller("MainController", function(){
var vm = this;
vm.title = 'AngularJS Nested Controller Example';
});
angular
.module('app')
.directive('nestedDirective', function() {
return {
restrict: 'E',
scope: {},
controller: 'nestedDirectiveController',
controllerAs: 'vm',
template:'<div> {{vm.message}} </div>'
};
});
angular
.module('app')
.controller('nestedDirectiveController', nestedDirectiveController);
function nestedDirectiveController() {
var vm = this;
this.message = "hoi";
}
Check the codepen if you would like: http://codepen.io/anon/pen/VeYxQg
Go through this link for more information
Upvotes: 1