Angular UI Bootstrap Modal更新$ scope

Tin*_*ino 10 angularjs angular-ui-bootstrap

我想使用模态来编辑我的数据.我将数据传递给模态实例.当我单击确定时,我将$ scope.selected中的已编辑数据传递回控制器.

在那里,我想更新原始的$ scope.不知何故,$ scope不会更新.我究竟做错了什么?

var ModalDemoCtrl = function ($scope, $modal, $log) {

  $scope.data = { name: '', serial: ''  }

  $scope.edit = function (theIndex) {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl,
      resolve: {
        items: function () {
          return $scope.data[theIndex];
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      $scope.selected = selectedItem;

      // this is where the data gets updated, but doesn't do it
      $scope.data.name = $scope.selected.name;
      $scope.data.serial = $scope.selected.serial;

    });
  };
};
Run Code Online (Sandbox Code Playgroud)

模态控制器:

var ModalInstanceCtrl = function ($scope, $modalInstance, items) {

  $scope.items = items;
  $scope.selected = {
    name: $scope.items.name,
    serial: $scope.items.serial
  };

  $scope.ok = function () {
    $modalInstance.close($scope.selected);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};
Run Code Online (Sandbox Code Playgroud)

莫代尔:

<div class="modal-header">
    <h3>{{ name }}</h3>
</div>
<div class="modal-body">
    <input type="text" value="{{ serial }}">
    <input type="text" value="{{ name }}">
</div>
<div class="modal-footer">
    <button class="btn btn-primary" ng-click="ok()">OK</button>
    <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
Run Code Online (Sandbox Code Playgroud)

Lar*_*ner 14

您没有为模态添加模板,所以这是一个猜测.您的代码非常接近于ng-repeat在模板中使用的angular-ui模式的示例代码.如果您正在做同样的事情,那么您应该知道ng-repeat创建一个继承自父级的子范围.

从这个片段判断:

$scope.ok = function () {
    $modalInstance.close($scope.selected);
};
Run Code Online (Sandbox Code Playgroud)

看起来好像不是在你的模板中这样做:

<li ng-repeat="item in items">
    <a ng-click="selected.item = item">{{ item }}</a>
</li>
Run Code Online (Sandbox Code Playgroud)

你可能会做这样的事情:

<li ng-repeat="item in items">
    <a ng-click="selected = item">{{ item }}</a>
</li>
Run Code Online (Sandbox Code Playgroud)

如果是这样,那么在您的情况下,您将selected在子范围中进行分配,这不会影响父范围的selected属性.然后,当您尝试访问时$scope.selected.name,它将为空.通常,您应该为模型使用对象,并在其上设置属性,而不是直接分配新值.

这部分文档更详细地解释了范围问题.

编辑:

您根本没有将输入绑定到任何模型,因此您输入的数据永远不会存储在任何位置.你需要用ng-model它来做,例如:

<input type="text" ng-model="editable.serial" />
<input type="text" ng-model="editable.name" />
Run Code Online (Sandbox Code Playgroud)

有关工作示例,请参阅此plunkr.