如何使用angularjs $modal來(lái)寫(xiě)一個(gè)公用的彈框插件?望詳解,謝謝。
學(xué)習(xí)是最好的投資!
我告訴你一個(gè)思路,但不會(huì)詳解,因?yàn)槲也幌矚g伸手黨……方案給你,最起碼動(dòng)腦子思考一下吧。
首先,以下程式碼用的不是ui-bootstrap 的$modal, 而是ng-strap 的$modal,原因是我覺(jué)得後者的程式碼品質(zhì)比前者好一些,不過(guò)後者比較新,API 沒(méi)有前者那麼完善,因此需要你有比較強(qiáng)的動(dòng)手能力,不過(guò)這和接下來(lái)要說(shuō)的擴(kuò)充$modal service 沒(méi)有關(guān)係。
其次,擴(kuò)充一個(gè)公用 $modal service 之前你得先考慮一下這些問(wèn)題:
這些問(wèn)題在一開(kāi)始是沒(méi)有明確答案的,但你需要在心裡模擬一個(gè)答案出來(lái),因?yàn)樗鼘Q定你的 service 如何寫(xiě)。
第一步,準(zhǔn)備預(yù)設(shè)的參數(shù);這是原 $modal 提供的參數(shù),先設(shè)定好一個(gè)初始狀態(tài)(依照自己的需求)
javascript
// 可以在入口模塊的 .config 里做 angular.extend($modalProvider.defaults, { animation: 'am-flip-x', container: 'body', templateUrl: 'components/angular-strap/modal.html' })
第二步:寫(xiě)新服務(wù)的屬性擴(kuò)充程式碼;讓新服務(wù)可以擁有和原 $modal 一樣的屬性擴(kuò)充能力
javascript
// 一樣,放在某個(gè)某塊的 config 里 .config(function ConfirmModalConfig($modalProvider, ConfirmModalProvider) { ConfirmModalProvider.defaults = angular.extend( $modalProvider.defaults, ConfirmModalProvider.defaults ) })
接著就是 ConfirmModal
的定義,最終返回的是 $promise,以便於調(diào)用者擴(kuò)展自己的業(yè)務(wù)邏輯;我在重點(diǎn)處加了些註釋,剩下的自己看明白:
javascript
function ConfirmModal() { // 新服務(wù)的默認(rèn)參數(shù),允許覆蓋 this.defaults = { html: true, templateUrl: 'components/angular-strap/confirm.html', contentTemplate: 'components/angular-strap/confirm-modal.html' } this.$get = function($q, $modal) { return { // 只需一個(gè) public method 足夠了 open: function _openConfirmModal(parentScope, options) { // 把調(diào)用者的 $scope 傳進(jìn)來(lái),生成新的 $scope 給自己,實(shí)現(xiàn) $scope 繼承 // 最大的用處:可以在 $modal 的模版里直接是用 parent $scope 里的屬性和方法 var _scope = parentScope.$new() // 給新 $scope 一個(gè) namespace,等價(jià)于 angular 的 controller as 語(yǔ)法 _scope.modalModel = {} // 合并默認(rèn)參數(shù)和用戶傳遞的參數(shù) var _options = angular.extend(_.clone(this.defaults), options) _options.scope = _scope // 創(chuàng)造 modal 實(shí)例 var _modal = $modal(_options) // 返回 promise,默認(rèn)給模版綁定兩個(gè)方法,一個(gè)用于確認(rèn),一個(gè)用于取消 // 如需要更多方法,則可以在 contentTemplate 里調(diào)用 parent $scope 的方法 // @params immediateHide: 布爾,用于指明觸發(fā)默認(rèn)綁定方法后是自動(dòng)關(guān)閉 $modal, // 還是留給調(diào)用者在 .then 里手動(dòng)關(guān)閉 return $q(function(resolve, reject) { _scope.modalModel.confirm = function(data, immediateHide) { if (immediateHide) { _modal.hide() resolve({data: data}) } else resolve({data: data, modal: _modal}) } _scope.modalModel.cancel = function(reason, immediateHide) { if (immediateHide) { _modal.hide() reject({reason: reason}) } else reject({reason: reason, modal: _modal}) } }) }.bind(this) } } }
呼叫實(shí)例:
javascript
// 在某處,通常是 controller 或 directive function SomeWhereController(ConfirmModal, Something, $state) { var vm = this vm.delete = function(something) { ConfirmModal.open($scope, { title: '確定要?jiǎng)h除嗎?' }) .then(function(result) { return Something.delete(something.id) }) .then(function(response) { $state.reload($state.current) }) .catch(console.error.bind(console)) } }
模版什麼的,參考原始的 $modal 自己改寫(xiě)就是了,代碼 github 上都有,就這樣。