如何在没有引导的情况下正确处理 AngularJS 应用程序中的弹出窗口(模态)

How to properly handle popups (modals) in AngularJS app without bootstrap

本文关键字:应用程序 窗口 模态 AngularJS 正确处理 情况下      更新时间:2023-09-26

我的应用程序中几乎没有弹出窗口。一个用于显示"关于",第二个用于显示联系表单。我目前所做的是将整个弹出 DOM 放入模板中并编写如下自定义指令:

angular.module('app').directive('contactForm', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {},
    templateUrl: 'contactForm.html',
    controller: function($scope) {
      $scope.submitForm = function() {
        ...  
      }
    },
    link: function(scope, el) {
      scope.$on('openContactForm', function() {
        el.show();
      });
    }
  }
});

并在我的索引中的某个地方调用此类指令.html

<body>
  <about-popup></about-popup>
  <contact-form></contact-form>
  ...
  ...
</body>

页面上的某个地方有这样的控制器,其功能绑定到按钮:

angular.module('app').controller('SideBarController', function($scope, $rootScope) {
  $scope.openContactForm = function() {
    $rootScope.$broadcast('openContactForm');
  }
});

我不觉得这是处理这个问题的最好方法,但不知道如何做得更好。你有什么想法,例子吗?

我做的最后一个应用程序需要一个简单的模式来显示消息,我的方式是使用与您的指令非常相似的指令。

该指令附加模板并使用$rootScope来存储模态对象,该对象具有属性 show(由模板中的 ng-show 使用)和每次我需要显示/隐藏模态窗口时调用的切换函数。因为对象在$rootScope所以你可以在任何地方使用它。

这是该指令的简化版本。

app.directive('myModal', ['$rootScope', function ($rootScope) {
    return {
    restric: 'A',
    replace: true,
    template: '<div class="modal" ng-show="modal.show">{{ modal.mainMessage }}<br /><button ng-click="modal.toggle()">Close</button></div>',
    link: function (scope, elm, attrs) {
       $rootScope.modal= {
          mainMessage: '',
          show: false,
          toggle: function (mainMessage) {
             this.mainMessage = mainMessage;
             this.show = !this.show;
          }
       };
     }
  };
}]);

这是一个JSBin。

这是一个很好的问题,我很好奇它会得到什么答案。