AngularJS模态范围

时间:2018-09-18 18:54:57

标签: angularjs

我对范围和模态感到困惑。

我想从模态进行的ajax调用中更新变量$ scope.message。我该怎么办?

angular.module('myApp').controller('x_ctrl', function ($scope, $http, $uibModal, $uibModalStack) {
  $scope.message = "start";
  $scope.open = function () {
    console.log("opening dialog");
        var modalInstance = $uibModal.open({
            templateUrl: "popup.html",
            controller: "x_ctrl",
            scope: $scope,
            size: "lg"
        });  
    modalInstance.result.then(function () {
    }, function () { 
    });
  }
  $scope.close = function() {
    console.log("getting test.json");
    $http({
    url: "test.json",
    method: "GET"
    })
    .then(function successCallback(response) {
      $scope.message = response.data.message;
      console.log($scope.message);
    });
    $uibModalStack.dismissAll();
  }
});

https://plnkr.co/edit/9xPAz18rcN2jfFqkwsX3?p=preview

1 个答案:

答案 0 :(得分:2)

I don't think the $uibModal will work well when you try to use the same controller you are displaying it from as the modal's controller. I recommend separating the two and then you can return the updated value from the modal to your calling controller. Here is an example that you should be able to adapt to your purposes (I didn't include the json file retrieval).

angular.module('app', ['ui.bootstrap'])
  .controller('ctrl', ($scope, $uibModal) => {
    $scope.message = 'start';
    $scope.open = () => {
      $uibModal.open({
        templateUrl: 'popup.html',
        controller: 'modalCtrl',
        size: 'lg',
        resolve: {
          message: () => $scope.message
        }
      }).result.then((data) => {
        $scope.message = data;
      });
    }
  })
  .controller('modalCtrl', ($uibModalInstance, $scope, message) => {
    $scope.message = message;
    $scope.close = () => {
      $uibModalInstance.close('some response message ' + moment().format('M/D/YY HH:mm:ss'));
    }
  });
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <button ng-click="open()">Open</button>
  <div>
    Message: {{ message }}
  </div>
  <script type="text/ng-template" id="popup.html">
    <div class="modal-body">
      Message: {{ message }}
    </div>
    <div class="modal-footer">
      <button class="btn btn-default" ng-click="close()">Close and update $scope.message</button>
    </div>
  </script>
</div>