我是一名 AngularJS 初学者,我很难让模式按照我想要的方式运行。 简而言之,问题是这样的:模式的“.then”部分中的代码在打开模式时运行,而不是在关闭模式时运行。请参阅我的代码下面的进一步说明。 我的 index.html 中有一个调用函数的按钮:
<button type="button" ng-click="addModal()" class="btn btn-default">
<span class="glyphicon glyphicon-plus"> Add account</span>
</button>
我的 Controller 定义如下所示:
app.controller('MyController', ['$scope','$http', '$modal',
'ModalService', function ($scope, $http, $modal, ModalService)
MyController 中的 addModal 函数如下所示:
$scope.addModal = function () {
console.log("addModal");
ModalService.showModal({
templateUrl: "/addAccount.html",
controller: "addController"
}).then(function(modal) {
modal.element.modal();
console.log('asd')
modal.close.then(function(result) {
console.log("Modal closed");
$scope.settings = {};
$scope.settings.balance = 0;
$scope.settings.runningTotals = 0;
$scope.settings.firstName = result.first;
$scope.settings.lastName = result.last;
$scope.settings.address = result.add;
$scope.settings.postcode = result.post;
$scope.settings.telephone = result.tele;
$scope.settings.pin = result.pin;
var json = JSON.stringify($scope.settings);
console.log(json);
console.log("Clicked button");
return $http.post("http://abcmoneygroup.cloudapp.net/Service1.svc/createAccount", json);
});
});
我正在使用this创建模态的服务。 我的模态 Controller 如下所示:
app.controller('addController', ['$scope','close', '$element', function ($scope, close, $element) {
$scope.first = null;
$scope.last = null;
$scope.add = null;
$scope.post = null;
$scope.tele = null;
$scope.pin = null;
$scope.close = function () {
console.log('close called')
close({
formfirstName: $scope.first,
formLastName: $scope.last,
formAddress: $scope.add,
formPostCode: $scope.post,
formTelephone: $scope.tele,
formPin: $scope.pin
}, 500);
};
$scope.cancel = function () {
$element.modal('hide');
close({
}, 500);
};
}]);
最后 addAccount.html 包含此按钮:
<button type="button" class="btn btn-success" ng-click="close()" data-dismiss="modal">
<span>Save new account</span>
</button>
我的问题是,当我第一次单击“添加帐户”按钮时,我的模式出现。在控制台中,我看到两行:“addModal”和“asd”。 在 addAccount.html 中填写表格后,我单击“保存新帐户”按钮。然后模式关闭,在控制台中我看到以下行:“关闭调用”。 为什么现在没有发起 Http.post 请求?
如果我现在再次单击“添加帐户”按钮,模式将打开,我会在控制台中看到以下几行:
- 添加模态
- 模态框关闭
- {"balance":0,"runningTotals":0}
- 已点击按钮
- asd
总而言之,我想知道为什么每次打开模态时都会启动 ModalService 的“.then”部分中的代码,而不是每次关闭它时。任何帮助将不胜感激,干杯!
最佳答案
根据 Angular ui Bootstrap 结果(类型:promise)的文档,当模式关闭时解析,当模式关闭时拒绝。
为了使您的代码看起来更干净,我建议您声明一个变量 modalInstance
然后使用结果来解决或拒绝 promise
modalInstance.result.then(function (result) {
console.log(result);
}, function () {
console.log('modal dismissed');
});
关于javascript - Angularjs 模式关闭时不运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34997979/