0

HTML templates can be used multiple times with supplied data as object in KnockoutJS, I am getting difficulties in finding the same feature with AngularJS. Take a look at below URL of KO documentation.

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>

You can observe how "buyer" and "seller" are passed as object to template, and rendered accordingly with Knockout JS.

I want similar implementation with AngularJS. Take a look at below example.

<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>

I tried something like above, but finally both ng-include will generate "test1" text. I want different result for both ng-include, for first "FirstValue" and for second "SecondValue"

Take a look at here: http://plnkr.co/edit/DQgPZ9GKKLnwSvOggY3M?p=preview

How can I pass data object to such html template and render accordingly?.

4

1 回答 1

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>

例子

于 2013-06-20T14:05:41.383 回答