CSharp
CSharp

Reputation: 1476

Modifying the scope of an Isolated Scope Directive in Angular

I'm trying to understand Isolated Scopes in directives. I have the following html:

<div new-test>
  <h4>new scope : {{msg}}</h4>
  <button ng-click="clicker()">new test</button>
  <hr>
</div>
<div same-test>
  <h4>same as parent scope : {{msg}}</h4>
  <button ng-click="clicker()">same test</button>
  <hr>
</div>
<div isolate-test>
  <h4>isolated scope : {{msg}}</h4>
  <button ng-click="clicker()">isolated test</button>
  <button ng-click="ftn()">own ftn</button>
  <hr>
</div>

And the following angular directives:

angular.module('myApp', []);

angular.module('myApp')

.directive('newTest', [function() {
    return {
    scope: true,
    link: function(scope, elem, attr) {
        scope.msg = 'new scope';
        scope.clicker = function() {
          console.log("New Scope");
        };
    }
  }
}])

.directive('sameTest', [function() {
    return {
    scope: false,
    link: function(scope, elem, attr) {
        scope.msg = 'same scope';
        scope.clicker = function() {
          console.log("Same Scope");
        };
    }
  }
}])

.directive('isolateTest', [function() {
    return {
    restrict: 'A',
    scope: {},
    link: function(scope, elem, attr) {
        scope.msg = 'isolated scope'; // this doesn't exist
        scope.clicker = function() {
          console.log("Isolated Scope"); // this is never called
        };
        scope.ftn = function() {
          console.log("own ftn"); // or this
        };
    }
  }
}]);

None of the functions or variables that I thought I added to the scope of the isolateTest directive exist. If I click the isolate test button, the clicker function in the same-test directive is getting called instead. How come? I thought that button exists in an isolated scope along with any other elements between the div elements? How can I add a 'local' function to the scope of an isolated directive like isolateTest? Here is the fiddle.

Can someone please explain what is happening here. Thanks!

Upvotes: 3

Views: 62

Answers (1)

lux
lux

Reputation: 8436

In your isolateTest directive, I switched your scope: {} to scope: true, and I'm able to get your functions to fire.

Updated fiddle: https://jsfiddle.net/rjcmjd0k/11/

.directive('isolateTest', [function() {
    return {
    restrict: 'A',
    scope: true,
    link: function(scope, elem, attr) {
        scope.msg = 'isolated scope';
        scope.clicker = function() {
       console.log("Isolated Scope");
      };
      scope.ftn = function() {
        console.log("own ftn");
      };
    }
  }
}]);

Upvotes: 1

Related Questions