AngularJS How to dynamically add HTML and bind to controller

后端 未结 5 1415
梦谈多话
梦谈多话 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:39

    I would use the built-in ngInclude directive. In the example below, you don't even need to write any javascript. The templates can just as easily live at a remote url.

    Here's a working demo: http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p=preview

    <p>Select page content template via dropdown</p>
    <select ng-model="template">
        <option value="page1">Page 1</option>
        <option value="page2">Page 2</option>
    </select>
    
    <p>Set page content template via button click</p>
    <button ng-click="template='page2'">Show Page 2 Content</button>
    
    <ng-include src="template"></ng-include>
    
    <script type="text/ng-template" id="page1">
        <h1 style="color: blue;">This is the page 1 content</h1>
    </script>
    
    <script type="text/ng-template" id="page2">
        <h1 style="color:green;">This is the page 2 content</h1>
    </script>
    
    0 讨论(0)
  • 2020-11-28 05:51

    There is a another way also

    1. step 1: create a sample.html file
    2. step 2: create a div tag with some id=loadhtml Eg : <div id="loadhtml"></div>
    3. step 3: in Any Controller

          var htmlcontent = $('#loadhtml ');
          htmlcontent.load('/Pages/Common/contact.html')
          $compile(htmlcontent.contents())($scope);
      

    This Will Load a html page in Current page

    0 讨论(0)
  • 2020-11-28 05:54

    See if this example provides any clarification. Basically you configure a set of routes and include partial templates based on the route. Setting ng-view in your main index.html allows you to inject those partial views.

    The config portion looks like this:

      .config(['$routeProvider', function($routeProvider) {
        $routeProvider
          .when('/', {controller:'ListCtrl', templateUrl:'list.html'})
          .otherwise({redirectTo:'/'});
      }])
    

    The point of entry for injecting the partial view into your main template is:

    <div class="container" ng-view=""></div>
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 05:57

    I needed to execute an directive AFTER loading several templates so I created this directive:

    utilModule.directive('utPreload',
        ['$templateRequest', '$templateCache', '$q', '$compile', '$rootScope',
        function($templateRequest, $templateCache, $q, $compile, $rootScope) {
        'use strict';
        var link = function(scope, element) {
            scope.$watch('done', function(done) {
                if(done === true) {
                    var html = "";
                    if(scope.slvAppend === true) {
                        scope.urls.forEach(function(url) {
                            html += $templateCache.get(url);
                        });
                    }
                    html += scope.slvHtml;
                    element.append($compile(html)($rootScope));
                }
            });
        };
    
        var controller = function($scope) {
            $scope.done = false;
            $scope.html = "";
            $scope.urls = $scope.slvTemplate.split(',');
            var promises = [];
            $scope.urls.forEach(function(url) {
                promises.add($templateRequest(url));
            });
            $q.all(promises).then(
                function() { // SUCCESS
                    $scope.done = true;
                }, function() { // FAIL
                    throw new Error('preload failed.');
                }
            );
        };
    
        return {
            restrict: 'A',
            scope: {
                utTemplate: '=', // the templates to load (comma separated)
                utAppend: '=', // boolean: append templates to DOM after load?
                utHtml: '=' // the html to append and compile after templates have been loaded
            },
            link: link,
            controller: controller
        };
    }]);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    
    <div class="container-fluid"
         ut-preload
         ut-append="true"
         ut-template="'html/one.html,html/two.html'"
         ut-html="'<my-directive></my-directive>'">
     
    </div>

    0 讨论(0)
提交回复
热议问题