Reputation: 8487
I have the following code. I read that directives can inherit objects and variables from their parent scopes. I have a controller with a child directive, but I can't seem to get my $scope.title
inside my directive.
Why is this?
https://plnkr.co/edit/h4YlRPa5ZWQkwPZ3isjZ?p=preview
var mod = angular.module('myApp', []);
mod.controller('myControl', controlFunc).directive('myDirec', direcFunc);
function controlFunc($scope){
$scope.title = "John Smith";
}
function direcFunc(){
return {
restrict: 'E',
template: '<h1>' + $scope.title + '</h1>'
};
}
Upvotes: 1
Views: 86
Reputation: 136154
The way you are trying to access the scope in directive, you must have get console error $scope is not defined
, as $scope
isn't directly available in directive.
You can't access variable on HTML directly using $scope
variable. You should either use angular directive for binding like ng-bind
/{{}}
(interpolation directive) will be helpful in this case.
Your directive template should be like below.
function direcFunc(){
return {
restrict: 'E',
scope: false, //by default false, means will not create a new scope
//template: '<h1>{{title}}</h1>', //alternative
template: '<h1 ng-bind="title"></h1>'
};
}
Currently what you are thinking isn't correct, here directive is not creating any kind of child scope. Basically by default directive is using scope: false
options, which says directive to don't create any scope use the existing one. If you wanted to confirm the directive scope is same as that of controller, then you could put console.log(scope)
inside directive link function.
function direcFunc(){
return {
restrict: 'E',
scope: false, //by default false, means will not create a new scope
//template: '<h1>{{title}}</h1>', //alternative
template: '<h1 ng-bind="title"></h1>',
link: function(scope, element, attrs){
console.log("Below scope will be same as that of controller");
console.log(scope);
}
};
}
Upvotes: 3