AngularJS将特定的数据绑定到模板中

AngularJS bind specific data to template

本文关键字:数据绑定 AngularJS      更新时间:2023-09-26

我正在从Knockout切换到Angular。我现在遇到的主要问题是把我的原始模板转换成Angular能识别的东西。

具体来说,这里有一段代码我在传输时遇到了麻烦:

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

在Knockout中,这将把Squares[5]附加到squaretemple,这样当模板被渲染时,它就会使用Squares[5]中的成员(或任何附加的数据)。

我需要为Squares[0]~Squares[11]重复这个过程。但我不能使用ng-repeat,因为我不会按数字顺序遍历它们。

理想情况下,如果我能在

这一行做点什么就好了

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

任何想法?

这是我写的一个JSFiddle,概述了我尝试使用ng-model的失败尝试。

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

两件事:首先,你可以使ng-data可用通过实现它自己YourApp.directive("ngData", function() {})其次,你需要的HTML是另一个文件的一部分吗?一个简单的方法来完成你在Angular中寻找的是ng-repeat,如:

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

Square数组被更新时,将会有一个额外的post。

查看修改后的JSFiddle: http://jsfiddle.net/TdWMF/1/

所以这主要是一个hack来实现你想要的,直到我能给你一个更好的解决方案:

第二次更新使用混合顺序ng-repeat: http://jsfiddle.net/TdWMF/3/

基本上

:

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

很丑,而且不理想,我知道。我还建议在函数中执行顺序数组生成,然后执行:ng-repeat="index in displayOrder(Squares)"