0

I have a modal component that takes an object with binding (ng-model). Something like:

<modal ng-model="modals.createContact"></modal>

I'm checking for $ctrl.ngModel.show to show/hide the modal:

<div class="modal" ng-show="$ctrl.ngModel.show" ng-transclude></div>

I show/hide modal by setting modals.createContact.show using ng-click directive:

<button ng-click="modals.createContact.show = true"></button>

But this solution is hard to maintain.

I need a directive something like this to toggle modal's show property:

<button modal="modals.createContact">Toggle modal</button>

Directive should listen the click event of the element (button) then toggle the $ctrl.modal.show property.

What I mean with toggling is:

$ctrl.modal.show = !$ctrl.modal.show;

How can achieve this scenario using directives?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Umut Çağdaş Coşkun
  • 1,197
  • 2
  • 15
  • 33

1 Answers1

1

To handle click events inside a directive be sure to use $apply:

app.directive("myDirective", function() {
    return {
        link: postLink
    }
    function postLink(scope, elem, attrs) {
        elem.on("click", function(ev) {
            scope.$apply(function() {
                //code here
            });
        });
    }
})

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc... You can also use $apply() to enter the AngularJS execution context from JavaScript.

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • Thank you for your reply. I'm passing an object to the directive, but it will come as string to the directive. How can I pass objects? I tried this in `$apply` but didn't work: `scope[attrs.modal].show = !scope[attrs.modal].show;` I put `modal="modals.createContact"` which is an object. When I log `typeof attrs.modal` it says "string". – Umut Çağdaş Coşkun Feb 01 '20 at 18:56
  • It is really hard to help with bugs in code when the question contains none of the buggy code. I wrote about objects as directive attributes in [mdDialog binding transforms object into a "object Object"](https://stackoverflow.com/a/60011817/5535245). – georgeawg Feb 01 '20 at 21:08