【问题标题】:How to show and hide element in my case如何在我的情况下显示和隐藏元素
【发布时间】:2015-07-01 23:32:23
【问题描述】:

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

我希望当用户做某事时弹出模式。我使用 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;
    }
}]) 

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

【问题讨论】:

    标签: angularjs modal-dialog using-directives


    【解决方案1】:

    加载指令后链接功能立即运行,所以在你的情况下,如果你只想在 $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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多