Last active
August 29, 2015 14:13
-
-
Save ChristiaanScheermeijer/0a2c88bc768243ec379b to your computer and use it in GitHub Desktop.
Dynamic controller directive
This file contains hidden or 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
'use strict'; | |
var DynamicControllerDirective = function ($parse, $compile, $templateRequest, $exceptionHandler) { | |
return { | |
restrict: 'A', | |
link: function (scope, element, attr) { | |
$templateRequest(attr.dynamicControllerTemplate).then(function (template) { | |
var templateElement = angular.element(template); | |
if (templateElement.length !== 1) { | |
return $exceptionHandler('dynamicControllerTemplate needs to have 1 child element'); | |
} | |
var controller = $parse(attr.dynamicController); | |
var childrenClone = templateElement.children().clone(); | |
element.html(templateElement); | |
scope.$watch(controller, function (newController) { | |
if (newController && newController !== templateElement.data('$ngControllerController')) { | |
if (templateElement.data('$scope')) { | |
templateElement.data('$scope').$destroy(); | |
} | |
templateElement.html(childrenClone); | |
templateElement.data('$ngControllerController', newController); | |
templateElement.data('$scope', newController.$scope); | |
$compile(templateElement)(newController.$scope); | |
} | |
}); | |
}); | |
} | |
}; | |
}; | |
// inject dependencies | |
DynamicControllerDirective.$inject = ['$parse', '$compile', '$templateRequest', '$exceptionHandler']; | |
// register directive | |
angular.module('dynamicControllerModule') | |
.directive('dynamicController', DynamicControllerDirective); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment