user3800799
user3800799

Reputation: 538

Angular modal directive - issue when having more than 1 in a page

I made a modal directive for my angular app.

modal-directive.js

'use strict';

backyApp.directive('appModal', function() {
    return {
        restrict: 'A',
        transclude: true,
        link: function($scope, elem, attr){
            $scope.modalClass = attr.appModal;
        },
        scope: '@',
        templateUrl: './components/modal/modal.html'
    };
});

and the template looks like this: (modal.html)

<!-- Modal -->
<div class="app-modal" ng-class="modalClass">
    <div ng-transclude></div>            
</div>

Now, let's pretend we have 2 modals in a page:

<div app-modal="firstModal">
    <div class="form-group">
            <input type="text"  />
            <input type="submit" value="Submit" />
        </div>
    </div>
</div>

<div app-modal="secondModal">
    <div class="form-group">
            <input type="text"  />
            <input type="submit" value="Submit" />
        </div>
    </div>
</div>

Problem: I end up with 2 modals having the same class (in my example above, secondModal will be attached to 2 of my modals)

Why does this happen? I need the value of my directive to be attached to each modal because thats the only way I can open the one I want.

I know this is horrible explanation Let me know if you have any question

Edit:

I want to have 2 app-modal divs, each one having its directive value as a class attached to it. Hope it's more clear now.

Upvotes: 0

Views: 112

Answers (1)

Srijith
Srijith

Reputation: 1444

Use an isolated scope in the directive

backyApp.directive('appModal', function() {
 return {
    restrict: 'A',
    transclude: true,
    link: function($scope, elem, attr){
        $scope.modalClass = attr.appModal;
    },
    scope: {},
    templateUrl: './components/modal/modal.html'
 };
});

Here is a plunker I did for this https://embed.plnkr.co/UwjBIqTh5fNlAcbIs6TS/

Upvotes: 2

Related Questions