31

我知道这已经被讨论过很多次,大多数文章都引用了这段代码:Modal window with custom URL in AngularJS

但我就是不明白。我觉得这根本不是很清楚。我还发现这个jsfiddle实际上很棒,非常有帮助,除了它不添加 url 并允许我使用后退按钮关闭模式。


编辑:这是我需要帮助的。

所以让我试着解释一下我想要达到的目标。我有一个添加新项目的表格,我有一个链接“添加新项目”。我想当我单击“添加新项目”时会弹出一个模式,其中包含我创建的“add-item.html”表单。这是一个新状态,因此 url 更改为 /add-item。我可以填写表格,然后选择保存或关闭。关闭,关闭模态:p(多么奇怪)。但我也可以单击返回以关闭模式并返回上一页(状态)。 在这一点上,我不需要 Close 的帮助,因为我仍在努力让模态正常工作。


这是我的代码:

导航控制器:(这甚至是放置模态函数的正确位置吗?)

angular.module('cbuiRouterApp')
  .controller('NavbarCtrl', function ($scope, $location, Auth, $modal) {
    $scope.menu = [{
      'title': 'Home',
      'link': '/'
    }];

    $scope.open = function(){

        // open modal whithout changing url
        $modal.open({
          templateUrl: 'components/new-item/new-item.html'
        });

        // I need to open popup via $state.go or something like this
        $scope.close = function(result){
          $modal.close(result);
        };
      };

    $scope.isCollapsed = true;
    $scope.isLoggedIn = Auth.isLoggedIn;
    $scope.isAdmin = Auth.isAdmin;
    $scope.getCurrentUser = Auth.getCurrentUser;

    $scope.logout = function() {
      Auth.logout();
      $location.path('/login');
    };

    $scope.isActive = function(route) {
      return route === $location.path();
    };
  });

这就是我激活模式的方式:

 <li ng-show='isLoggedIn()' ng-class='{active: isActive("/new-item")}'>
   <a href='javascript: void 0;' ng-click='open()'>New Item</a>
 </li>

新项目.html:

<div class="modal-header">
  <h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
  <ul>
    <li ng-repeat="item in items"><a ng-click="selected.item = item">{{ item }}</a></li>
  </ul>Selected:<b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
  <button ng-click="ok()" class="btn btn-primary">OK</button>
  <button ng-click="close()" class="btn btn-primary">OK</button>
</div>

此外,虽然这确实打开了一个模式,但它并没有关闭它,因为我无法解决这个问题。

4

4 回答 4

56

将模态视为状态的视图组件是很直观的。使用视图模板、控制器和一些解析来进行状态定义。这些特征中的每一个也适用于模态的定义。更进一步,将状态输入链接到打开模式,将状态退出链接到关闭模式,如果你可以封装所有管道,那么你就有了一种机制,可以像状态一样使用ui-sref$state.go用于进入和后退按钮或更多特定于模式的退出触发器。

我对此进行了相当广泛的研究,我的方法是创建一个模态状态提供程序,它可以类似于$stateProvider配置模块以定义绑定到模态的状态时使用。当时,我特别感兴趣的是通过状态和模态事件来统一对模态解除的控制,这比你要求的要复杂,所以这里有一个简化的例子

关键是让模态成为状态的责任,并使用模态提供的钩子使状态与模态通过范围或其 UI 支持的独立交互保持同步。

.provider('modalState', function($stateProvider) {
    var provider = this;
    this.$get = function() {
        return provider;
    }
    this.state = function(stateName, options) {
        var modalInstance;
        $stateProvider.state(stateName, {
            url: options.url,
            onEnter: function($modal, $state) {
                modalInstance = $modal.open(options);
                modalInstance.result['finally'](function() {
                    modalInstance = null;
                    if ($state.$current.name === stateName) {
                        $state.go('^');
                    }
                });
            },
            onExit: function() {
                if (modalInstance) {
                    modalInstance.close();
                }
            }
        });
    };
})

状态输入启动模态。状态出口将其关闭。模态可能会自行关闭(例如:通过背景点击),因此您必须观察并更新状态。

这种方法的好处是您的应用程序继续主要与状态和与状态相关的概念进行交互。如果您稍后决定将模式转换为常规视图,反之亦然,则只需更改很少的代码。

于 2014-07-13T19:18:32.287 回答
8

这是一个provider通过将resolve部分向下传递给来改进@nathan-williams 解决方案的方法controller

.provider('modalState', ['$stateProvider', function($stateProvider) {
  var provider = this;

  this.$get = function() {
    return provider;
  }

  this.state = function(stateName, options) {
    var modalInstance;

    options.onEnter = onEnter;
    options.onExit = onExit;
    if (!options.resolve) options.resolve = [];

    var resolveKeys = angular.isArray(options.resolve) ? options.resolve : Object.keys(options.resolve);
    $stateProvider.state(stateName, omit(options, ['template', 'templateUrl', 'controller', 'controllerAs']));

    onEnter.$inject = ['$uibModal', '$state', '$timeout'].concat(resolveKeys);
    function onEnter($modal, $state, $timeout) {
      options.resolve = {};

      for (var i = onEnter.$inject.length - resolveKeys.length; i < onEnter.$inject.length; i++) {
        (function(key, val) {
          options.resolve[key] = function() { return val }
        })(onEnter.$inject[i], arguments[i]);
      }

      $timeout(function() { // to let populate $stateParams
        modalInstance = $modal.open(options);
        modalInstance.result.finally(function() {
          $timeout(function() { // to let populate $state.$current
            if ($state.$current.name === stateName)
              $state.go(options.parent || '^');
          });
        });
      });
    }

    function onExit() {
      if (modalInstance)
        modalInstance.close();
    }

    return provider;
  }
}]);

function omit(object, forbidenKeys) {
  var prunedObject = {};
  for (var key in object)
    if (forbidenKeys.indexOf(key) === -1)
      prunedObject[key] = object[key];
  return prunedObject;
}

然后像这样使用它:

.config(['modalStateProvider', function(modalStateProvider) {
  modalStateProvider
    .state('...', {
      url: '...',
      templateUrl: '...',
      controller: '...',
      resolve: {
        ...
      }
    })
}]);
于 2016-06-08T10:26:36.530 回答
2

我回答了一个类似的问题,并在此处提供了一个示例:

AngularJS中带有自定义URL的模态窗口

有一个完整的工作 HTML 和一个指向 plunker 的链接。

于 2014-12-03T23:18:25.580 回答
0

The $modal itself doesn't have a close() funcftion , I mean If you console.log($modal) , You can see that there is just an open() function.

Closing the modal relies on $modalInstance object , that you can use in your modalController.

So This : $modal.close(result) is not actually a function!

Notice : console.log($modal); ==>> result :

          Object { open: a.$get</k.open() }
           // see ? just open ! , no close !

There is some way to solve this , one way is :

First you must define a controller in your modal like this :

   $modal.open({
      templateUrl: 'components/new-item/new-item.html',
      controller:"MyModalController"
    });

And then , Later on , :

    app.controller('MyModalController',function($scope,$modalInstance){
      $scope.closeMyModal = function(){
       $modalInstance.close(result);
        }
       // Notice that, This $scope is a seperate scope from your NavbarCtrl,
       // If you want to have that scope here you must resolve it

   });
于 2014-07-12T14:09:42.670 回答