我试图通过服务公开使用Angular的$ uibModal的“通用”模式。这是该服务的定义:
angular.module('app').service('CustomModalService', ['$uibModal', function ($uibModal) { var openCustomModal = function (size, title, message) { var actionToPerformOnConfirm = action; var modalInstance = $uibModal.open({ templateUrl : 'templates/CustomModal.html', size: size, resolve: { title: title, message: message } }); }; return { openCustomModal: openCustomModal }; }]);
上面没有什么太复杂的。但是,它不起作用。如果我resolve从对象中删除该属性,则该服务有效;但是,如果包含该resolve属性,则会收到源自该属性的未知提供程序错误。
resolve
该resolve属性的文档为:
(类型:对象)-将被解析并作为本地成员传递给控制器的成员;它等效于路由器中的resolve属性。
目的是能够为在其DOM中利用这些属性的模态提供模板,例如:
<div ng-controller="CustomModalController"> <div class="modal-header"> <h3 class="modal-title">{{title}}</h3> </div> <div class="modal-body"> {{message}} </div> <div class="modal-footer"> <button class="ad-button ad-blue" type="button" ng-click="confirmAction()"></button> <button class="ad-button ad-blue" type="button" ng-click="cancelAction()"></button> </div> </div>
我缺少什么导致此错误引发?
您有两个问题:
string
function
工作示例:JSFiddle
angular.module('myApp', ['ui.bootstrap']) .controller('MyModalController', MyModalController) .directive('modalTrigger', modalTriggerDirective) .factory('$myModal', myModalFactory) ; function MyModalController($uibModalInstance, items) { var vm = this; vm.content = items; vm.confirm = $uibModalInstance.close; vm.cancel = $uibModalInstance.dismiss; }; function modalTriggerDirective($myModal) { function postLink(scope, iElement, iAttrs) { function onClick() { var size = scope.$eval(iAttrs.size) || 'lg'; // default to large size var title = scope.$eval(iAttrs.title) || 'Default Title'; var message = scope.$eval(iAttrs.message) || 'Default Message'; $myModal.open(size, title, message); } iElement.on('click', onClick); scope.$on('$destroy', function() { iElement.off('click', onClick); }); } return { link: postLink }; } function myModalFactory($uibModal) { var open = function (size, title, message) { return $uibModal.open({ controller: 'MyModalController', controllerAs: 'vm', templateUrl : 'templates/CustomModal.html', size: size, resolve: { items: function() { return { title: title, message: message }; } } }); }; return { open: open }; }
<script type="text/ng-template" id="templates/CustomModal.html"> <div class="modal-header"> <h3 class="modal-title">{{vm.content.title}}</h3> </div> <div class="modal-body"> {{vm.content.message}} </div> <div class="modal-footer"> <button class="ad-button ad-blue" type="button" ng-click="vm.confirm()"> confirm </button> <button class="ad-button ad-blue" type="button" ng-click="vm.cancel()"> cancel </button> </div> </script> <button modal-trigger size="'sm'" title="'Hello World!'" message="'This is a test'"> Click Me </button>