【问题标题】:Dynamically load HTML elements in AngularJS在 AngularJS 中动态加载 HTML 元素
【发布时间】:2014-12-03 23:35:06
【问题描述】:

当谈到 AngularJS 时,我是一个完整的初学者,过去我把所有的时间都花在了 jQuery 上。我要做的是从数据源读取页面内容,填充各种 HTML 元素,然后显示它们。

所以我拥有的是这个,content.json:

{
    "1" : {
        "Type" : "Title",
        "Content" : "Welcome to this Site"
    },
    "2" : {
        "Type" : "TextBox",
        "Content" : "<p>Introduction 1</p><p>Continued</p>"
    },
    "3" : {
       "Type" : "TextBox",
        "Content" : "<p>Do these tasks</p>"
    }
}

然后是一个 HTML 页面,其中包含:

<div ng-app="myapp">
    <div ng-controller="content" id="Content">
        <!-- Dynamic content to be loaded here -->
    </div>
</div>

我有几个简单的模板,TextBox.html:

<div class="TextBox">{{Content}}</div>

和 Title.html :

<h1>{{Content}}</h1>

最后是我的 AngularJS 代码:

var app = angular.module('myapp', []);
app.controller('content', ['$scope','$http',function($scope,$http) {

    $http.get('content.json').success(function(data){
        $scope.elements = data;

        // What do I do now?
    });
}]);

是否可以遍历 JSON 数据,加载由“Type”属性定义的模板,使用“Content”属性填充它,然后在“#Content”div 中显示所有元素?我该怎么做?

这是在 AngularJS 中处理此类任务的正确方法吗?我觉得我可能正在以 jQuery 的心态来处理这个问题,我想在我走得太远之前检查一下。

【问题讨论】:

标签: angularjs


【解决方案1】:

首先使用数组,而不是字典:

[
    {
        "id": "1",
        "Type" : "Title.html",
        "Content" : "Welcome to this Site"
    },
    {
        "id" :"2",
        "Type" : "TextBox.html",
        "Content" : "<p>Introduction 1</p><p>Continued</p>"
    },
    {
       "id": "3",
       "Type" : "TextBox.html",
        "Content" : "<p>Do these tasks</p>"
    }
]

其次,使用 ng-init 为 Content 设置别名,使用 ng-include 加载模板。重复您的收藏:

<div ng-app="myapp">
    <div ng-controller="content" id="Content">
        <!-- Dynamic content to be loaded here -->
        <div ng-repeat="item in elements" ng-init="Content=item.Content">
             <ng-include src="item.Type"></ng-include>
        </div>
    </div>
</div>

【讨论】:

  • 成功了,谢谢!但是,我必须进行一些小的更改:我的模板需要 ng-bind-html="Content" 才能正确呈现 HTML,并且 ng-include 的 src 需要变为 src="item.Type+' .html'"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
  • 2014-03-31
  • 2013-01-14
  • 1970-01-01
  • 2011-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多