Skip to content

Instantly share code, notes, and snippets.

@pswai
Last active August 29, 2015 14:12
Show Gist options
  • Save pswai/c8dd1c3ef8f3f04a02e7 to your computer and use it in GitHub Desktop.
Save pswai/c8dd1c3ef8f3f04a02e7 to your computer and use it in GitHub Desktop.
AngularStrap $modal Controller and Resolve
// Dependency: underscore.js or lodash
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 options = _.omit(config, ['controller', 'controllerAs', 'resolve']); // Options to be passed to $modal()
var modalScope = options.scope || $rootScope;
// Resolve
if (config.resolve) {
resolvePromises = _
.map(config.resolve, function (resolveFunc) {
return $injector.invoke(resolveFunc);
});
}
// Setup controller
if (config.controller) {
allDone = $q.all(resolvePromises)
.then(function (resolves) {
var locals = {};
// Assign resolves
var iter = 0;
_.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
_.assign(options, {
scope: modalScope
});
return $delegate(options);
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment