I have a 2D array that is iterated through via ng-repeat
. This array is actually part of a spreadsheet app I am building, where the initial values in the spreadsheet are that of the array. I wrote a function that would update this array as the user changed input values, however, I've been informed that I need to use the $watch
method instead of an onchange
method.
我有一个通过ng-repeat迭代的2D数组。这个数组实际上是我正在构建的电子表格应用程序的一部分,其中电子表格中的初始值是数组的初始值。我编写了一个函数,可以在用户更改输入值时更新此数组,但是,我已经被告知我需要使用$ watch方法而不是onchange方法。
I'm really thrown off because I don't understand how I can change the initial array's values through the $watch
method. I see that it detects change, but I want it to keep track of that change and actually alter the initial array.
我真的被抛弃,因为我不明白如何通过$ watch方法更改初始数组的值。我看到它检测到变化,但是我希望它能够跟踪这个变化并实际改变初始数组。
Here is my Javascript, including the beginnings of a $watch
method:
这是我的Javascript,包括$ watch方法的开头:
sheet= function($scope, $parse){
$scope.columns = headers;
$scope.rows = allData.length;
$scope.cells = {};
$scope.$watch(
function() {console.log("Change!");},
);
$scope.values = allData.map(function(c,row){
return c.map(function(data){
return {
content: data,
model: null,
color: makeColors(data)
};
});
});
};
changeData = function(row, col, data){
allData[row][col] = data;
};
My HTML:
我的HTML:
<div ng-app ng-controller="sheet">
<table>
<tr class="column-label">
<td ng-repeat="column in columns">{{column}}</td>
<tr ng-repeat="value in values">
<td class="row-label" ng-repeat="data in value">
<div>
<input type="text" id="inputValue" ng-model="data.content" class="{{data.color}}" onchange="changeData({{$parent.$index}},{{$index}},this.value)">
</div>
</td>
</tr>
</table>
</div>
As you can see, I call the changeData function using the $parent.$index
and $index
values, which allow me to access and change the initial array. I'm unsure how to do this via $watch
.
如您所见,我使用$ parent。$ index和$ index值调用changeData函数,这允许我访问和更改初始数组。我不确定如何通过$ watch来做到这一点。
1 个解决方案
#1
4
Your $watch is missing the value it's watching. It won't do anything without that.
你的$ watch缺少正在观看的价值。没有它,它不会做任何事情。
But why are you going through such trouble to update your model? Your model is updated automatically when you bind ng-model to an input.
但是你为什么要经历这样的麻烦来更新你的模型呢?将ng-model绑定到输入时,会自动更新模型。
Here is a plunker showing how I would approach it: http://plnkr.co/edit/Oxu1NV?p=preview
这是一个关于我如何接近它的人:http://plnkr.co/edit/Oxu1NV?p=preview
#1
4
Your $watch is missing the value it's watching. It won't do anything without that.
你的$ watch缺少正在观看的价值。没有它,它不会做任何事情。
But why are you going through such trouble to update your model? Your model is updated automatically when you bind ng-model to an input.
但是你为什么要经历这样的麻烦来更新你的模型呢?将ng-model绑定到输入时,会自动更新模型。
Here is a plunker showing how I would approach it: http://plnkr.co/edit/Oxu1NV?p=preview
这是一个关于我如何接近它的人:http://plnkr.co/edit/Oxu1NV?p=preview