Tag Archives: adding scripts

Angular js – Adding scripts dynamically

I have been learning and trying to implement couple of things using Angularjs and Nancy.
NancyFx with owin is fun to start with. I am adding couple of things that took some time to implement and to find online also.

Adding scripts dynamically:
in the main controller add the below function

            $scope.loadScript = (function (url, type, charset) {
            if (typeof (type) == 'undefined') type = 'text/javascript';
            if (url) {
                var script = document.querySelector("script[src*='" + url + "']");
                if (!script) {
                    var heads = document.getElementsByTagName("head");
                    if (heads && heads.length) {
                        var head = heads[0];
                        if (head) {
                            script = document.createElement('script');
                            script.setAttribute('src', url);
                            script.setAttribute('type', type);
                            if (charset) script.setAttribute('charset', charset);
                return script;

and in the child controller add the below function

$scope.$parent.loadScript('../Scripts/libs/prism.js', 'text/javascript', 'utf-8');