dk123
dk123

Reputation: 19700

AngularJS bind specific data to template

I'm currently making a switch from Knockout to Angular. The main problem I'm having right now is in transferring my original templates to something Angular will recognise.

Specifically, here's a bit of code I'm having trouble transferring:

<!-- ko template: { name: 'SquareTempl', data: Squares[5] } --><!-- /ko -->

In Knockout, this will attach Squares[5] to SquareTempl, so that when the template gets rendered, it does so using the members within Squares[5](or whatever data that gets attached).

I need to repeat the process for Squares[0]~Squares[11]. I can't use ng-repeat though since I won't be iterating through them in numerical order.

Ideally, it would be nice if I could do something along the lines of

<td class="Square" id="five" ng-include src="'SquareTempl.html'" ng-data="Squares[5]">

Any ideas?

Here's a JSFiddle I've written to outline a failed attempt I've tried using ng-model.

http://jsfiddle.net/fZz3W/9/

Upvotes: 0

Views: 329

Answers (1)

Brandon Buck
Brandon Buck

Reputation: 7181

Two things: First, you can make ng-data be available by implementing it yourself YourApp.directive("ngData", function() {}) Secondly, do you need the HTML to be part of another file? An easy way to accomplish what you're looking for in Angular is with ng-repeat like:

<td ng-repeat="item in Square">
    <div>{{item.name}}</div> 
</td>

When the Square array is updated an additional post will be made.

Review your modified JSFiddle: http://jsfiddle.net/TdWMF/1/

So this is mostly a hack to achieve what you want, until I can offer you a better solution:

Second update using mixed order ng-repeat: http://jsfiddle.net/TdWMF/3/

Basically:

<div ng-repeat="index in [4, 2, 0, 3, 1]">
   square index: {{index}}<br />
   square: {{Squares[index]}}
</div>

Pretty ugly, and non-ideal, I know. I'd also recommend performing the order array generate in a function and then doing: ng-repeat="index in displayOrder(Squares)"

Upvotes: 2

Related Questions