Alex Man
Alex Man

Reputation: 4886

AngularJS directive working together unexpectly

I have created an an angularjs directive for a drop-down box, The directive is working fine but the issue is that when I replicate the directive then both are working simultaneously opening, selection and closing

<div ng-app='myApp' ng-controller="Controller">
    <drop-down></drop-down>
    <br> <br> <br> <br> <br> <br>
    <drop-down></drop-down>
</div>

Can anyone please tell me some solution for this

JSFIddle

Upvotes: 2

Views: 72

Answers (3)

Michael Kang
Michael Kang

Reputation: 52867

Add scope:true to your directive:

app.directive('dropDown', function ($parse, $document) {
    return {
        restrict: 'E',
        scope:true,
        ...
    }
});

By specifying scope: true, each directive will create its own child scope that inherits from the parent scope, and will not affect each other.

If you don't specify scope:true, then each directive is sharing data from parent scope (in this case, parent scope is the controller's scope), which explains why the behavior of both directives are linked.

Demo

Upvotes: 5

mohamedrias
mohamedrias

Reputation: 18566

It's because both the directives are in the same controller. So the directive is using same scope.

In that case, you must either use isolated scope to create separate scope for the directives. Or must wrap the multiple directives with different controllers.

In your directive code: add scope: {}

app.directive('dropDown', function ($parse, $document) {
    return {
        restrict: 'E',
        require: ['?ngModel'],
        scope: {},
        template: ...

   }

DEMO

Upvotes: 3

Shaxrillo
Shaxrillo

Reputation: 769

Just add scope: {} in your directive Fiddle

Upvotes: 3

Related Questions