AngularJS中的HTML模板,如KnockoutJS

时间:2013-06-20 12:49:12

标签: angularjs knockout.js angular-template

HTML模板可以多次使用提供的数据作为KnockoutJS中的对象,我在使用AngularJS找到相同的功能时遇到了困难。请查看以下KO文档的URL。

http://knockoutjs.com/documentation/template-binding.html

<div data-bind="template: { name: 'person-template', data: buyer }"></div>
<div data-bind="template: { name: 'person-template', data: seller }"></div>

<script type="text/html" id="person-template">
    <h3 data-bind="text: name"></h3>
    <p>Credits: <span data-bind="text: credits"></span></p>
</script>

<script type="text/javascript">
     function MyViewModel() {
         this.buyer = { name: 'Franklin', credits: 250 };
         this.seller = { name: 'Mario', credits: 5800 };
     }
     ko.applyBindings(new MyViewModel());
</script>

您可以观察“买家”和“卖家”如何作为对象传递给模板,并使用Knockout JS进行相应的渲染。

我想要与AngularJS类似的实现。看看下面的例子。

<script type="text/ng-template" id="someId">{{name}}</script>

<ng-include src="'someId'" onload="name='FirstValue'" ></ng-include>
<ng-include src="'someId'" onload="name='SecondValue'" ></ng-include>

我尝试了类似上面的内容,但最后两个ng-include都会生成“test1”文本。对于第一个“FirstValue”和第二个“SecondValue”,我想要ng-include的不同结果

请看这里:http://plnkr.co/edit/DQgPZ9GKKLnwSvOggY3M?p=preview

如何将数据对象传递给此类html模板并进行相应的渲染?

1 个答案:

答案 0 :(得分:2)

如果您想重复使用模板,可以创建包含范围的directives

<强>模板

<script type="text/ng-template" id="someId.html"><span>{{name}}</span></script>

<强>指令

myApp.directive("myTemplate", function () {
    return {
        restrict: "E",
        scope: {
            name: "="
        },
        replace: true,
        templateUrl: "someId.html"
    };
});

用法

<my-template name="name"></my-template>

<强> Example