不要在角度模态中保存范围更改

时间:2016-03-01 15:00:33

标签: angularjs modal-dialog angular-ui-bootstrap

我正在使用Angular UI Bootstrap模式来更新作用域上的数组。除非我单击关闭按钮,否则我不希望保存更改。如果我单击“关闭”按钮,我不想更新阵列。 (这真的是尝试模态功能)

我遇到了一些问题。当我在控制器中包含$ modalInstance时,我收到以下错误: 错误:[$ injector:unpr]未知提供者:$ modalInstanceProvider< - $ modalInstance< - ModalInstanceController 这似乎与AngularJS inject issue with Angular Bootstrap modal相似,但我的模板中没有ng-controller。

另一个问题是,当我尝试修改数组时,它会在模态之外更新。我正在使用$scope.users.push( 'Dave' );。官方演示似乎是以同样的方式进行,所以当我在$ uibModal上调用open方法时,它是否可以通过我传递范围的方式?

这是Plunk: http://plnkr.co/edit/FuXjSwtljQtFYOtFRV18?p=preview

1 个答案:

答案 0 :(得分:1)

我在你的plunker中修改了你的js代码,它应该让你朝着正确的方向前进。它修复了注入器错误,并且不会更新$ scope.users,除非您单击“关闭”。按Esc关闭模态不应该调用'ok'方法。

var app = angular.module('modalExample', ['ui.bootstrap']);

app.controller('ModalDemoController', ['$scope', '$uibModal', function($scope, $uibModal){
  console.log('modal');

  $scope.users = ['Adam', 'Brian', 'Clive'];

  $scope.open = function(){
    var modalInstance = $uibModal.open({
      templateUrl: 'modal.html',
      scope: $scope,
      controller: 'ModalInstanceController',
      resolve: {
        users: function() {
          return $scope.users;
        }
      }
    });

    modalInstance.result.then(function(modalUsers) {
      //this replaces the array with the array from the modal
      $scope.users = modalUsers;
    })
  };

}]);


// Modal controller is only used for the modal while it's open
app.controller('ModalInstanceController', ['$scope', 'users', '$uibModalInstance', function($scope, users, $uibModalInstance){
  $scope.modalUsers = angular.copy(users);
  $scope.ok = function() {
    //this will pass your modified array into the modalInstance.result.then call
    $uibModalInstance.close($scope.modalUsers)
  };

  //make some other methods for modifying $scope.modalUsers
}])

在你的模态html中,将ng-repeat更改为引用modalUsers:

<p>Existing users:</p>
  <ul>
    <li ng-repeat="user in modalUsers">{{user}}</li>
  </ul>
相关问题