如何在我的案例中显示和隐藏元素

时间:2015-07-01 23:32:23

标签: angularjs modal-dialog using-directives

我正在尝试创建一个指令模式,以便我可以在其他地方使用。

我想在用户做某事时弹出模态。我使用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;
    }
}]) 

出于某种原因,我无法隐藏模态,并且在页面首次加载时总是会弹出。如何在首次加载页面时成功隐藏它?谢谢你的帮助!

1 个答案:

答案 0 :(得分: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>