给定HTML模板
<div class="info">
<div class="title"><a href="property-detail.html">{{title}}</a></div>
<div class="location">{{location}}</div>
<div class="property-info clearfix">
<div class="area"><i class="icon icon-normal-cursor-scale-up"></i>{{size}}<sup>2</sup></div>
<div class="bedrooms"><i class="icon icon-normal-bed"></i>{{bedrooms}}</div>
<div class="bathrooms"><i class="icon icon-normal-shower"></i>{{bathrooms}}</div>
</div><div class="price">{{price}}</div>
<div class="link">
<a href="{{details}}">View more</a>
</div>
</div>
适合此模板的模型(即具有所有字段:标题,位置,价格等)。我正在寻找一种方法,以编程方式将模板绑定到模型,然后将渲染的结果推送到数组。在伪代码中,我希望做类似的事情:
var boxes= [];
for (var i = 0; i < items.length; i++) {
var results = bind(template, items[i]);
boxes.push(results);
}
其中items是我从数据库或任何其他源获得的项目数组,而bind基本上是负责用模型填充模板的函数。
使用指令是有意义的。不知道如何做到这一点。
知道是否以及如何使用Angular完成它?
答案 0 :(得分:0)
通常,您不希望在指令之外的任何操作中操作DOM。但为什么要教条呢呢?如果你真的需要一个字符串格式的编译模板(对于第三方小部件消费或类似的东西),那么你可以组合一个类似于以下的服务:
angular.module('app', []);
angular.module('app').controller('MainCtrl', function ($scope, templateCompiler) {
var boxes = [];
var data = [{
title: 'test',
location: 'location!',
size: 40,
bedrooms: 'yes',
bathrooms: 'uncertain',
price: 'if you have to ask...',
details: 'indeterminate'
},{
title: 'test2',
location: 'somewhere',
size: 'a woman never tells',
bedrooms: 3.14,
bathrooms: null,
price: 1400,
details: 'forthcoming'
}];
for (var i = 0; i < data.length; i++) {
var results = templateCompiler.bind(data[i]);
boxes.push(results);
}
$scope.boxes = boxes;
})
angular.module('app').service('templateCompiler', function ($compile, $templateCache, $rootScope) {
var service = {}
var template = $templateCache.get('boxTemplate');
var scope;
this.bind = function (data) {
scope = $rootScope.$new();
angular.extend(scope, data);
var link = $compile(template);
var content = link(scope);
scope.$apply();
return content.html();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app='app'>
<script type="text/ng-template" id="boxTemplate">
<div class="info">
<div class="title"><a href="property-detail.html">{{title}}</a></div>
<div class="location">{{location}}</div>
<div class="property-info clearfix">
<div class="area"><i class="icon icon-normal-cursor-scale-up"></i>{{size}}<sup>2</sup></div>
<div class="bedrooms"><i class="icon icon-normal-bed"></i>{{bedrooms}}</div>
<div class="bathrooms"><i class="icon icon-normal-shower"></i>{{bathrooms}}</div>
</div><div class="price">{{price}}</div>
<div class="link">
<a href="{{details}}">View more</a>
</div>
</div></script>
<!-- TO PROVE YOU GET THE DESIRED OUTPUT -->
<div ng-controller="MainCtrl">{{boxes}}</div>
</div>
您也可以考虑将地图窗口小部件包装在指令中。