AngularJS (v1) – components (dynamic directives)

Date: 2016-07-26
(function () {
    'use strict';

    angular
    .module('app.services')
    .factory('componentService', ['$http', '$q', '$controller', '$compile', '$rootScope',
    function ($http, $q, $controller, $compile, $rootScope) {
        var exports = {};

        exports.newFromUrl = function(controllerFn, templateUrl) {
            var defer = $q.defer();
            $http.get(templateUrl).then(function(result) {
                var template = result.data;
                var el = exports.new(controllerFn, template);
                defer.resolve(el);
            }, defer.reject);
            return defer.promise;
        };

        exports.new = function(controllerFn, templateStr) {
            var scope = $rootScope.$new(); // Create new scope, inherit from rootscope
            var controller = $controller(controllerFn, { $scope: scope }); // create new controller, inject our $scope
            var linkFn = $compile(templateStr); // compile the template
            var content = linkFn(scope); // apply the scope to the template, the scope is set/controlled by the controller
            return content; // result: a HTMLElement, with our scope applied
        };

        //example
        exports.example = function() {            
            exports.newFromUrl(['$scope','$rootScope', function($scope, $rootScope) {
                $scope.title = 'hoi';
            }], 'app/directives/directive/directive.html')
            .then(function(result) {
                var el = result;
                var parent = document.getElementById('componentParent');
                parent.appendChild(el[0]);
            });
        };

        return exports;
    }]);
}());
4020cookie-checkAngularJS (v1) – components (dynamic directives)