我花了一些时间玩AngularJS Bootstrap弹出窗口,实际上它运行得很好,但我想做的是将它绑定到同一个控制器,它依赖于脚本,但我现在无法使用关闭按钮。如果我创建了一个新的控制器,并注入$modalInstance,它工作得很好,我可以在没有任何问题的情况下连接关闭按钮,但我不想要第二个控制器,这似乎过于复杂了:我真的希望我的所有控制器逻辑都在formController中。
为什么我真的想要两个控制器?在两个控制器之间传递作用域对我来说似乎有些过头了,而且项目越大,就越不可管理。我是不是试图不必要地过度简化?:)
脚本:
(function(){
var app = angular.module('ngModalDemo', ['ui.bootstrap'])
.controller('formController', function($scope, $modal){
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: 'SomeModal.html',
controller: 'formController'
});
};
$scope.closeModal = function () {
// Code needed here :)
};
})
})();
HTML正文(为了演示的目的,请原谅脚本中的HTML):
<div ng-controller="formController">
<button class="btn btn-default" ng-click="openModal()">Let's do some stuff!</button>
<script type="text/ng-template" id="SomeModal.html">
<div class="modal-header">Do some stuff in this modal y'all.</div>
<div class="modal-footer">
<button class="btn btn-info" ng-click="closeModal()">Close</button>
</div>
</script>
</div>
基于Kaspars输入的答案:)
(function(){
var app = angular.module('ngModalDemo', ['ui.bootstrap'])
.controller('formController', function($scope, $modal, $log){
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: 'SomeModal.html',
controller: [
'$scope', '$modalInstance', function($scope, $modalInstance){
$scope.closeModal = function () {
$modalInstance.close();
};
}
]
});
};
})
})();
我也遇到了同样的问题,我想到的最好的办法是使用匿名函数作为模式控制器。这样,所有的逻辑都在同一个控制器中,您不必为每个模式窗口创建单独的控制器。
这看起来像这样:
(function(){
var app = angular.module('ngModalDemo', ['ui.bootstrap'])
.controller('formController', function($scope, $modal){
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: 'SomeModal.html',
controller: [
'$scope', '$modalInstance', 'data', function($scope, $modalInstance, data) {
$scope.data = data;
$scope.ok = function() {
$modalInstance.close();
};
$scope.closeModal = function() {
$modalInstance.dismiss();
};
}
]
});
};
})
})();
PS。还没有测试过上面的代码,只是把你提供的代码和我的一个项目的片段放在一起。
您也可以尝试这个
var modalInstance = $modal.open({
templateUrl : 'someTemplate.html',
scope : $scope,
size : 'md'
});