novalain
novalain

Reputation: 2209

Directive scope

I have a directive in angular and a form which is bound to a scope variable. Code:

<my-directive></my-directive>

<form>
    <input ng-model="username" required>
</form>

Directive:

.directive('myDirective', function(){
    restrict : 'E',
    controller: function($scope){
        console.log($scope.username); // Displays user name, same scope!!!
    },
    link: function(scope, element, attrs){
       // Other codes
    },
    templateUrl: "templates/my-template-url.html"
  }
})

The username variable can be reached inside the controller in my directive. This is not why I expected since I close the directive and they shouldn't share the same scope?

Why does this work?

Upvotes: 0

Views: 39

Answers (1)

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Well you are using scope:false . It can access and change it's parent scope.

So your node scope doesn't matter here because username is in it's parent scope.

<my-directive></my-directive>

<form>
    <input ng-model="username" required>
</form>

If your don't wanna to access parent scope then create an isolate scope

Like this

.directive('myDirective', function(){
    restrict : 'E',
    scope : {},
    controller: function($scope){
        console.log($scope.username); // Displays user name, same scope!!!
    },
    link: function(scope, element, attrs){
       // Other codes
    },
    templateUrl: "templates/my-template-url.html"
  }
})

Upvotes: 5

Related Questions