I have included my code below:
// HTML
<body>
<h1>{{foo.name}}</h1>
<my-directive></my-directive>
</body>
// Scripts
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
scope: true, //**********
template: '<h4>{{foo.name}}</h4>',
controllerAs: 'foo',
controller: fooCtrl,
link: function(scope) {
console.log(scope);
}
}
});
var fooCtrl = function() {
this.name = 'FOO';
}
My Query:
When I utilize the controllerAs syntax and do not set scope: true in myDirective, the controller becomes global and inserts foo.name into Tag. However, when scope is set to true, the controller only applies to myDirective.
Why does this happen? Does a controller inside a directive create a new scope that inherits from the surrounding scope? Why does it apply globally?
UPDATE
Mistakenly, I forget about using isolate scope before, so please disregard my confusion regarding the usage of scope inside directives. After reading the docs again, I now have a clear understanding. Thank you for the answer!