I am learning AngularJS 1 right now and am confused about scope and directive controllers. I don't understand why my directive controller has access to all the variables defined in the controller that is controlling the view in which the directive has been placed, given that I've inserted an empty isolate scope into my directive and as well as a bindToController object that references only one of the view's controller's variables.
Index.html
<!doctype html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"></head>
</head>
<body>
<div ng-controller='MainController as ctrl'>
<div class="container">
<basic-directive id= "ctrl.here"></basic-directive>
</div>
</div>
<script src="js/angular.js"></script>
<script src="js/app/app.js"></script>
<script src="js/app/controllers/MainController.js"></script>
<script src="js/app/directives/basicDirective.js"></script>
</body>
</html>
MainController.js
function MainController() {
ctrl = this;
ctrl.here = "Hello World";
ctrl.nowhere = "Hello Nowhere";
};
angular
.module('app')
.controller('MainController', MainController);
basicDirective.js
function basicDirective () {
return {
scope: {},
template: [
'<p>{{ basic.id }} </p>',
'<p>{{ basic.there }} <p>',
'<p>{{ basic.somewhere }}</p>'
].join(""),
controller: function () {
dr = this;
dr.there = ctrl.here
dr.somewhere = ctrl.nowhere
},
controllerAs: "basic",
bindToController: {id: "="}
}
}
angular
.module('app')
.directive('basicDirective', basicDirective);
Which renders:
<basic-directive id="ctrl.here" class="ng-isolate-scope">
<p class="ng-binding">Hello World </p>
<p class="ng-binding">Hello World </p>
<p class="ng-binding">Hello Nowhere</p>
</basic-directive>
My current understanding up until now had me expecting that only the first "Hello World" would render because that is the only one I bound to my directive's controller. Obviously there's something I'm missing. Can someone explain? And is there any practical difference between dr.there
and dr.id
in my directive controller?
p.s. Bear in mind for purposes of posting here I simplified my code to deal with only this issue, so the directive as written is definitely very contrived.