我需要基于JSON创建新的HTML元素(在我的情况下为复选框)。尝试根据书中内容数组的类型获取列出的每本书的复选框。但是我需要进一步循环以在单击复选框时为每本书找到选择数组,并为该特定书的已售副本和剩余副本创建文本框。当单击特定的复选框(书)时,在“选择”数组上找到并创建文本框(每个文本用于售出副本和剩余副本)会有所帮助。预先感谢
mybooks.json
"mycollection" : {
"title" : "Books",
"contents" : [
{
"title" : "Book1",
"type" : "CHECKBOX"
},
{
"title" : "Book2",
"type" : "CHECKBOX"
},
{
"title" : "Book3",
"type" : "CHECKBOX",
"onSelection" : [
{
"title" : "Sold Copies",
"type" : "TEXT"
},
{
"title" : "Remaining Copies",
"type" : "TEXT"
}
]
},
{
"title" : "Book4",
"type" : "CHECKBOX",
"onSelection" : [
{
"title" : "",
"type" : "TEXT"
}
]
}
]
}
templates.json
{
"textboxTemplate": "<input type='text' name='firstname'>",
"checkboxTemplate": "<div style='margin-top:70px,margin-left:50px'><label class='containerr'><input type='checkbox' id = 'myCheck' checked='checked'><span class='checkmarkk'></span></label><div id='personalhis_title' style='margin-left:30px'>{{content.title}}</div></div>"
}
app.js
var app = angular.module('myApppli', []);
app.config(function ($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist(['self', '**']);
});
app.constant('URL', 'json/');
app.factory('BookService', function ($http, URL) {
var getBooks = function () {
return $http.get(URL + 'mybooks.json');
};
return {
getBooks: getBooks
};
});
app.factory('TemplateService', function ($http, URL) {
var getTemplates = function () {
return $http.get(URL + 'templates.json');
};
return {
getTemplates: getTemplates
};
});
app.controller('contl', function (BookService) {
var ctrll = this;
ctrll.content = [];
ctrll.fetchContent = function () {
BookService.getBooks().then(function (result) {
ctrll.content = result.data.mycollection.contents;
});
};
ctrll.fetchContent();
});
app.directive('contentItem', function ($compile, TemplateService) {
var getTemplate = function (templates, type) {
var types = type.type;
var template = '';
switch (types) {
case 'textbox':
template = templates.textboxTemplate;
break;
case 'CHECKBOX':
template = templates.checkboxTemplate;
break;
}
return template;
};
var linker = function (scope, element, attrs) {
TemplateService.getTemplates().then(function (response) {
var templates = response.data;
element.html(getTemplate(templates, scope.content));
$compile(element.contents())(scope);
});
};
return {
restrict: 'E',
link: linker,
scope: {
content: '='
}
};
});
index.html
<div id="containerr" ng-controller="contl as ctrll">
<content-item ng-repeat="item in ctrll.content" content="item">
</content-item>
</div>