Using ui-router with Bootstrap-ui modal

后端 未结 4 1427
暗喜
暗喜 2020-11-28 21:22

I know this has been covered many times and most articles refer to this bit of code: Modal window with custom URL in AngularJS

But I just don\'t get it. I don\'t fin

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 21:58

    Here is a provider that improves @nathan-williams solution by passing resolve section down to the 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;
    }
    

    then use it like that:

    .config(['modalStateProvider', function(modalStateProvider) {
      modalStateProvider
        .state('...', {
          url: '...',
          templateUrl: '...',
          controller: '...',
          resolve: {
            ...
          }
        })
    }]);
    

提交回复
热议问题