AngularJS 如何动态添加 HTML 并绑定到控制器

AngularJS How to dynamically add HTML and bind to controller

本文关键字:HTML 绑定 控制器 添加 何动态 动态 AngularJS      更新时间:2023-09-26

我刚刚开始使用angularJS,正在努力为我正在做的事情找出合适的架构。 我有一个单页应用程序,但 URL 应始终保持不变;我不希望用户能够导航到根以外的任何路由。 在我的应用程序中,有一个主要的div 需要托管不同的视图。 当访问新视图时,我希望它接管主div 中的显示。 以这种方式加载的视图可以丢弃或隐藏在 DOM 中 - 我有兴趣看看每个视图如何工作。

我想出了一个粗略的工作示例来说明我正在尝试做的事情。 请参阅此 Plunk 中此处的工作示例。 基本上,我想将HTML动态加载到DOM中,并让标准的angularJS控制器能够挂接到新的HTML。 有没有比使用我这里的自定义指令并使用 $compile() 连接到 angular 更好/更简单的方法? 也许有类似路由器的东西,但不需要 URL 有更改才能运行?

这是我到目前为止使用的特殊指令(取自另一个 SO 帖子):

// Stolen from: http://stackoverflow.com/questions/18157305/angularjs-compiling-dynamic-html-strings-from-database
myApp.directive('dynamic', function ($compile) {
  return {
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        if (!html) {
            return;
        }
        ele.html((typeof(html) === 'string') ? html : html.data);
        $compile(ele.contents())(scope);
      });
    }
  };
});

谢谢

安 迪

我会使用内置的ngInclude指令。在下面的示例中,您甚至不需要编写任何 JavaScript。模板可以轻松地存在于远程 URL 上。

这是一个工作演示: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>
还有

另一种方式

  1. 步骤 1:创建示例.html文件
  2. 第 2 步:创建一个带有一些 id=loadhtml 的div 标签,例如:<div id="loadhtml"></div>
  3. 第 3 步:在任何控制器

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

这将在当前页面中加载一个 html 页面

对于那些像我这样无法使用角度指令并且被"卡"在角度范围之外的人来说,这里有一些可能对你有所帮助的东西。

在 Web 和 angular 文档上搜索数小时后,我创建了一个编译 HTML 的类,将其放置在目标中,并将其绑定到范围(如果没有该元素的$scope,则$rootScope

/**
 * 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;
})();

它涵盖了我的所有案例,但如果您发现我应该添加的内容,请随时发表评论或编辑。

希望它会有所帮助。

看看这个例子是否提供了任何澄清。基本上,您可以配置一组路由并包含基于路由的部分模板。在主索引中设置 ng-view.html允许您注入这些分部视图。

配置部分如下所示:

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

分部视图注入主模板的入口点是:

<div class="container" ng-view=""></div>
我需要在

加载多个模板后执行一个指令,所以我创建了这个指令:

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>