我根据教程编写了这段代码。我想知道如何使用单个 Controller 。我想仅使用 Controller 来生成此对话框。
http://fiddle.jshell.net/adnu6mmt/2/?utm_source=website&utm_medium=embed&utm_campaign=adnu6mmt
在这个项目中,我当前使用 2 个 Controller 。谢谢。
最佳答案
您需要保存模式实例并在同一 Controller 中使用它。首先,您需要像这样更改 html:
<div ng-app="myApp">
<script type="text/ng-template" id="myModal.html">
<div class="modal-header">
<h3 class="modal-title">Modal title</h3>
</div>
<div class="modal-body">
Modal content
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="close(true)">OK</button>
<button class="btn btn-warning" ng-click="close(false)">Cancel</button>
</div>
</script>
<div ng-controller="MyCtrl">
<input type="button" value="Show modal" ng-click="showModal()"/>
</div>
然后在你的 Controller 中:
.controller("MyCtrl", function($scope, $modal) {
var modalInstance = null;
$scope.close = function (ok, hide) {
if(ok) {
alert('ok');
} else {
alert('cancel');
}
modalInstance.dismiss();
};
var modalScope = $scope.$new();
$scope.showModal = function() {
modalInstance = $modal.open({
templateUrl: 'myModal.html',
scope: modalScope
});
}
});
当您想要在同一 Controller 中控制模态时,您需要访问它,请注意我们将 $modal
的结果存储在变量中以供以后使用。
这相当于将 modalInstance
注入(inject)到另一个 Controller ,让您可以访问该对象上的 close
、dismiss
或其他函数。
关于javascript - 在单个 Controller 中生成一个对话框。 Angular.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41172723/