我添加了一个Angular UI Modal,将范围传递给Modal Window进行2种方式绑定。我使用了该resolve方法来传递范围值。这样做可以起到一定的作用,这意味着当ng- model值在父级中更改时,它会在模态窗口内反映出来。但是,如果值在模态窗口内更改,则不会在父ng模型中反映出来。这是我的代码:
resolve
HTML:
<div ng-app="app"> <div ng-controller="ParentController"> <br /> <input type="text" ng-model="textbox.sample" /> <a class="btn btn-default" ng-click="open(textbox.sample)">Click Me</a> <script type="text/ng-template" id="ModalContent.html"> <input type = "text" ng-model= "ngModel" / > </script> <br />{{ textbox }} </div> </div>
控制器:
var app = angular.module('app', ['ui.bootstrap']); app.controller('ParentController', function ($scope, $modal) { $scope.textbox = {}; // MODAL WINDOW $scope.open = function (_ngModel) { // The ngModel is passed from open() function in template var modalInstance = $modal.open({ templateUrl: 'ModalContent.html', controller: ModalInstanceCtrl, resolve: { ngModel: function () { return _ngModel; } } // end resolve }); }; }); var ModalInstanceCtrl = function ($scope, $modalInstance, ngModel) { $scope.ngModel = ngModel; };
为什么在上面的代码中isint父实例和模态实例之间的2种方式绑定不起作用?
我认为您ng-model="textbox.sample"对父级和ng- model="ngModel"模态中的印象是相同的,因为您将传递textbox.sample给模态,并且能够在模态窗口中看到正确的值。起作用的唯一原因是因为$scope.ngModel每次打开模态窗口时都要显式设置属性。
ng-model="textbox.sample"
ng- model="ngModel"
textbox.sample
$scope.ngModel
使这项工作达到预期效果的一种方法是仅$scope.textbox.sample在两个地方都使用该属性,但我不建议这样做。
$scope.textbox.sample
也许正确的方法是使用modalInstance.result诺言,如下所示:
modalInstance.result
在模态上创建一个按钮并使其 ng-click="ok()"
ng-click="ok()"
$scope.ok = function () { $modalInstance.close($scope.ngModal); // will return this to the modalInstance.result }
然后在父控制器中,或通过任何方式打开模式窗口:
$scope.open = function (_ngModel) { // The ngModel is passed from open() function in template var modalInstance = $modal.open({ templateUrl: 'ModalContent.html', controller: ModalInstanceCtrl, resolve: { ngModel: function () { return _ngModel; } } // end resolve }); modalInstance.result.then(function (result) { $scope.textbox.sample = result; }); };