Last active
August 29, 2015 14:12
-
-
Save pswai/359102cea1f251542eda to your computer and use it in GitHub Desktop.
AngularStrap $modal Controller and Resolve without Lodash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('ps.modalOpen') | |
.config(function ($provide) { | |
'use strict'; | |
// Use decorator to add new functionality | |
$provide.decorator('$modal', function ($controller, $delegate, $injector, $q, $rootScope) { | |
// Add new open() method | |
$delegate.open = open; | |
return $delegate; | |
////////// | |
/* | |
* $modal.open() function | |
* | |
* This function adds new options to `$modal()`. | |
* | |
* New options: | |
* - controller {String|Function} First param of $controller. For string, controllerAs syntax is supported. | |
* - controllerAs {String} The 'as X' part of controllerAs syntax. | |
* - resolve {Object} Like the resolve in ngRoute | |
* | |
* Notes: | |
* -- Use either `controller: myCtrl as vm` or `controllerAs: vm`. Don't use both. | |
* -- Not sure if ngAnnotate supports this. It should since it understands '$modal.open()' in UI Bootstrap | |
*/ | |
function open(config) { | |
var ctrl, resolvePromises = []; | |
var allDone; | |
var modalScope = config.scope || $rootScope; | |
// Resolve | |
if (config.resolve) { | |
angular.forEach(config.resolve, function (resolveFunc) { | |
resolvePromises.push($injector.invoke(resolveFunc)); | |
}); | |
} | |
// Setup controller | |
if (config.controller) { | |
allDone = $q.all(resolvePromises) | |
.then(function (resolves) { | |
var locals = {}; | |
// Assign resolves | |
var iter = 0; | |
angular.forEach(config.resolve, function (resolveFunc, name) { | |
locals[name] = resolves[iter++]; | |
}); | |
// Create new scope | |
modalScope = modalScope.$new(); | |
locals.$scope = modalScope; | |
// Instantiate controller | |
ctrl = $controller(config.controller, locals); | |
if (config.controllerAs) { | |
modalScope[config.controllerAs] = ctrl; | |
} | |
}); | |
} | |
return allDone.then(function () { | |
// Prepare final options. We are deleting the additional options to ensure this is future proof. | |
var options = angular.copy(config); | |
delete options.controller; | |
delete options.controllerAs; | |
delete options.resolve; | |
angular.extend(options, { | |
scope: modalScope | |
}); | |
return $delegate(options); | |
}); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment