今天我遇到了一个有趣的 AngularJS 问题,我想我会发布:
在我的应用程序中,我有一个模型,我使用 ng-repeat 从它创建一个 HTML 表,另外我有一个与另一个模型相关联的输入字段,并且我已经向该模型注册了一个监视函数。当我在输入字段中输入一些文本时,该函数将该文本写入表的当前选定单元格。
一旦函数完成,就会发生一些连线的事情。不是更新所选单元格的值,而是在当前位置插入一个新单元格,然后将单元格向右移动,并从行中删除最后一个单元格。显然,我希望单元格保持其当前位置并且仅更新子元素。
这是我的代码的一个简短示例。该模型:
//The model is initialized with empty strings, later the input is supplied by the user
$scope.master.rows = [["", "", ""], ["", "", ""], ["", "", ""]];
HTML 片段:
<table ng-model="master.rows">
<tr ng-repeat="row in master.rows">
<td ng-repeat="col in row"
ng-click="master.click($event.target)">{{ col }}</td>
</tr>
</table>
当 click 函数执行时,当前单元格被设置在范围内,这样 watch 函数可以从中检索 x 和 y 索引并使用它来更新模型:
$scope.$watch("master.attributes", function (value) {
var x = $scope.master.current[0].cellIndex;
var y = $scope.master.current[0].parentNode.rowIndex;
$scope.master.rows[y][x] = value;
});