Thomas Hodges Thomas Hodges - 2 months ago 14
AngularJS Question

"controller as" with isolate scope in directives not isolating

I'm trying to learn to build custom directives in AngularJS. Presently I am using AngularJS 1.5.8.

I am trying to create an example of a directive with an isolate scope where the controller scope is not visible, so that I can selectively expose things by adding them to 'scope: {}.' In this example, what I expect to get is 'Name: Street:' because ctrl.customer should be unavailable to the directive. Then later I would add "customer: '='" to "scope: {}" and I would get "Name:David Street:123 anywhere street". Unfortunately, I am getting "Name:David Street:123 anywhere street" from this directive as it is written.

things I have tried:


  • setting "bindToController: true"

  • removing "scope: {}" and setting "bindToController: {}" (so I add "customer: '='" to that)

  • setting "bindToController: false" (might as well, right?)

  • repeatedly hitting shift-F5 after loading the html so make sure that I just don't have the old file cached.



testScope.js:

var app = angular.module('scopeModule',[]);

app.controller('Controller',[function(){
var vm = this;
vm.customer = {
name: 'David',
street: '123 anywhere street'
};
}]);

app.directive('sharedScope', function() {
return{
scope:{},
template: 'Name:{{ctrl.customer.name}} Street:{{ctrl.customer.street}}',
controller: 'Controller',
controllerAs: 'ctrl',
bindToController: true
};
});


index2.html:

<!doctype html>
<html ng-app="scopeModule">
<body>
<shared-scope></shared-scope>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="testScope.js"></script>
</body>
</html>

Answer

Controller is the controller of sharedScope directive. It is a single entity. this in directive's controller is ctrl in directive's template, because both controller and template belong to a directive.

There's no reason to isolate directive's scope from itself.

Isolated scope is isolated from the scopes of other directives. From the reference:

{...} (an object hash): A new "isolate" scope is created for the directive's element. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.

This means that if sharedScope directive has no controller and parent directive has Controller controller, this

  <div ng-controller="Controller as ctrl">
    <shared-scope></shared-scope>
  </div>

will result in

Name: Street:

output.