user2465164
user2465164

Reputation: 937

Changing values in an array with AngularJS $watch

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.

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.

Here is my Javascript, including the beginnings of a $watch method:

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:

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

Upvotes: 4

Views: 9044

Answers (1)

Sharondio
Sharondio

Reputation: 2614

Your $watch is missing the value it's watching. It won't do anything without that.

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.

Here is a plunker showing how I would approach it: http://plnkr.co/edit/Oxu1NV?p=preview

Upvotes: 4

Related Questions