Aleyna
Aleyna

Reputation: 1857

AngularJS scope variable won't persist inside a directive with isolate scope

I can't set a scope variable inside my custom directive's controller.

See this plkr: http://plnkr.co/edit/KVGVxhgRHxkhCLytkLBv?p=preview

Link function prints the variable name but interpolator does not evaluate {{name}}. I set it in the controller of my custom directive with isolate scope. Still for some reason, scope variable does not persist. Is this behavior expected? If so what is the proper way to set scope variables?

Help is appreciated.

Upvotes: 1

Views: 2780

Answers (2)

Michael Kang
Michael Kang

Reputation: 52847

Import 'name' from your outside scope into your isolated scope using '=' binding:

// Code goes here
angular.module('test', [])
  .directive('nametag', function() {
    return {
      scope: { name: '='},
      controller: function($scope, $attrs, $log) {
        $scope.name = 'John Doe';
      },
      link: function(scope, elem, attrs) {
        // elem.text(scope.name);
      }
    };
  });

HTML:

<div ng-app="app" ng-init="name='james'>
    <nametag name="name"></nametag>
</div>

When you define an isolated scope for your directive (by specifying scope: {}) you create a private scope that does not prototypically inherit from the parent scope. You can think of an isolated scope as your directive's private sandbox.

Since your directive's scope is isolated, you need to import scope variables from parent scope into your isolated scope through attribute bindings. In this case we are establishing two-way binding between the parent scope variable 'name', and the directive's isolated scope variable with the same name.

Upvotes: 3

Reto Aebersold
Reto Aebersold

Reputation: 16624

Your directive controller assigns the name to the isolated scope of the directive. So you have two possibilities:

  1. Remove the scope: {} from your directive to not create an isolated scope. While this works it is maybe not what you want as your directive modifies the outer scope.

  2. Add a template to your diective containing the <h1>Hello {{name}}</h1>. See this plunker.

Upvotes: 2

Related Questions