0

I am trying to create a directive modal so i can use on other place.

I want the modal to pop when user do something. I use ng-show to hide it.

my html

 <my-modal ng-show="showModal" data-text="my text"></my-modal>

my directive

angular.module('myApp').directive('myModal', ['$modal',
    function($modal) {
        return {
            restrict: 'E',
            scope: false,
            link: function(scope, elem, attrs) {              
                $modal({
                    template: '<div>{{scope.attrs.text}}</div>'
                    scope: scope,
                });
            }
        };
    }
]);

My controller

angular.module('myApp').controller('tCtrl', ['$scope',
    function($scope) {
        $scope.showModal = false;
    }
}]) 

For some reason, I can't hide modal and it always pops when the page first loads. How do I successfully hide it when the page first loads? Thanks for the help!

BonJon
  • 779
  • 1
  • 7
  • 21

1 Answers1

0

The link function runs as soon as the directive is loaded, so in your case, if you only want to show your modal once $scope.showModal = true, you have to modify your directive:

angular.module('myApp').directive('myModal', ['$modal',
    function($modal) {
        return {
            restrict: 'E',
            scope: {
              display: '=',
            },
            link: function(scope, elem, attrs) {            

              scope.$watch('display', function(newVal, oldVal) {
                if(newVal !== oldVal && newVal) {
                  $modal({
                      template: '<div>{{scope.attrs.text}}</div>',
                      scope: scope
                  });
                }
              });
            }
        };
    }
]);

And change your html to

<my-modal display="showModal" data-text="my text"></my-modal>
yvesmancera
  • 2,915
  • 5
  • 24
  • 33