AngularJS How to dynamically add HTML and bind to controller

后端 未结 5 1543
梦谈多话
梦谈多话 2020-11-28 05:25

I\'m just getting started with angularJS and struggling to figure out proper architecture for what I\'m trying to do. I have a single page app but the URL always sh

5条回答
  •  日久生厌
    2020-11-28 05:55

    For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.

    After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope if there is no $scope for that element)

    /**
     * AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
     */
    var AngularHelper = (function () {
        var AngularHelper = function () { };
    
        /**
         * ApplicationName : Default application name for the helper
         */
        var defaultApplicationName = "myApplicationName";
    
        /**
         * Compile : Compile html with the rootScope of an application
         *  and replace the content of a target element with the compiled html
         * @$targetDom : The dom in which the compiled html should be placed
         * @htmlToCompile : The html to compile using angular
         * @applicationName : (Optionnal) The name of the application (use the default one if empty)
         */
        AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
            var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
    
            $injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
                //Get the scope of the target, use the rootScope if it does not exists
                var $scope = $targetDom.html(htmlToCompile).scope();
                $compile($targetDom)($scope || $rootScope);
                $rootScope.$digest();
            }]);
        }
    
        return AngularHelper;
    })();
    

    It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.

    Hope it will help.

提交回复
热议问题