programing

Bootstrap-ui 모달과 함께 ui 라우터 사용

lovejava 2023. 4. 4. 20:22

Bootstrap-ui 모달과 함께 ui 라우터 사용

이 내용은 여러 번 다루어졌으며 대부분의 기사에서는 다음과 같은 코드를 언급하고 있습니다.사용자 지정 URL이 Angular에 있는 Modal 창JS

하지만 이해가 안 돼요나는 그것이 전혀 명확하지 않다고 생각한다.jsfiddle도 발견했는데, 정말 도움이 되었습니다.단, URL을 추가하지 않고 뒤로 버튼을 사용하여 모드를 닫을 수 있습니다.


편집: 이것이 도움이 필요한 부분입니다.

그래서 내가 무엇을 달성하려고 하는지 설명해보겠다.새로운 아이템을 추가할 수 있는 폼이 있고 '새로운 아이템 추가' 링크가 있습니다.'신규 아이템 추가'를 클릭하면 제가 만든 '추가 아이템' 폼이 뜨는 모달입니다.html'. 이것은 새로운 상태이므로 URL이 /add-item으로 변경됩니다.양식을 작성한 후 저장 또는 닫기를 선택할 수 있습니다.[닫기(Close)], [모달 :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>

new-item.syslog:

<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>

또한 이것은 모달(modal)을 여는 반면, 나는 그것을 해결할 수 없었기 때문에 닫지 않는다.

모달(modal)을 상태의 뷰 컴포넌트로 생각하는 것은 직관적입니다.뷰 템플릿, 컨트롤러 및 일부 해결 방법을 사용하여 상태 정의를 수행합니다.이러한 각 특성은 모달의 정의에도 적용됩니다.한 걸음 더 나아가 스테이트 엔트리를 모달 오픈으로 링크하고 스테이트 엔트리를 모달 클로즈로 링크합니다.모든 배관을 캡슐화할 수 있다면 스테이트 엔트리와 마찬가지로 사용할 수 있는 메커니즘이 있습니다.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();
                }
            }
        });
    };
})

스테이트 엔트리에 의해 모달은 기동됩니다.스테이트 exit에 의해 닫힙니다.모달은 자동으로 닫힐 수 있으므로(예: 배경 클릭을 통해), 이를 관찰하고 상태를 업데이트해야 합니다.

이 접근법의 이점은 앱이 주로 상태 및 상태 관련 개념과 계속 상호 작용한다는 것입니다.나중에 모달(modal)을 일반적인 뷰로 바꾸거나 반대로 바꾸기로 결정하면 변경할 코드가 거의 없습니다.

, 여기 ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ.provider@ @notic @notic @nothic @nothic @ @nothic @nothic @nothic @nothic @resolve을 나누다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: {
        ...
      }
    })
}]);

저는 비슷한 질문에 답하고 여기에 예를 제시했습니다.

사용자 지정 URL이 Angular에 있는 Modal 창JS

완전한 HTML과 plunker에 대한 링크가 있습니다.

$modal 자체에는 close() funcftion이 없습니다.즉, console.log($modal)를 사용하면 open() 함수만 있는 것을 알 수 있습니다.

모달의 종료는 $modal에 의존합니다.modalController에서 사용할 수 있는 인스턴스 객체.

따라서 $modal.close(결과)는 실제로는 함수가 아닙니다.

주의: console.log(모달); ==> 결과:

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

이 문제를 해결할 수 있는 몇 가지 방법이 있습니다.

먼저 다음과 같이 모달에 컨트롤러를 정의해야 합니다.

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

그 후, 나중에 :

    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

   });

언급URL : https://stackoverflow.com/questions/24713242/using-ui-router-with-bootstrap-ui-modal