Question

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

Was it helpful?

Solution

If you want to reuse templates you can create directives which contain a scope.

Template

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

Directive

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

Usage

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

Example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top