Ted Scheckler
Ted Scheckler

Reputation: 1521

AngularJS modal scope

I'm confused on the scope and modals.

I'd like to update a variable, $scope.message, from an ajax call made from a modal. How can I do that?

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

Upvotes: 0

Views: 922

Answers (1)

Lex
Lex

Reputation: 7194

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>

Upvotes: 2

Related Questions