2015-07-01 45 views
0

我想創建一個指令模態,所以我可以在其他地方使用。如何在我的情況下顯示和隱藏元素

我希望模式在用戶做某事時彈出。我用ng-show來隱藏它。

我的HTML

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

我的指令

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, 
       }); 
      } 
     }; 
    } 
]); 

我控制器

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

出於某種原因,我不能隱藏模式,它總是彈出當第一次加載頁面。如何在頁面首次加載時成功隱藏它?謝謝您的幫助!

回答

0

的鏈接功能,一旦該指令被加載運行,所以你的情況,如果你只是想顯示你的模式一度$ scope.showModal = true,則必須修改指令:

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 
        }); 
       } 
       }); 
      } 
     }; 
    } 
]); 

並將您的html更改爲

<my-modal display="showModal" data-text="my text"></my-modal>