Link to home
Start Free TrialLog in
Avatar of rationalJay
rationalJay

asked on

Adding function to Json Array in AngularJS

I have this JSON object returned from webapi,

[{name:John,val1:10,val2:20,val3:0},
{name:Jane,val1:50,val2:200,val3:0}]

Open in new window


I store this array in "$scope.dtArray" which is bound to the UI(textboxes) using ng-repeat. before the binding happens I want to assign a function to add values as shown here

this.val3 = function() {return Number(this.val1) + Number(this.val2) };

for each object in the array. SO when ever the user changes the val1 and val2 text boxes, the value changes for val3 automatically.

Following is the UI markup...

<div ng-repeat="cnt in dtArray track by $index">
    <table style="border-style: solid;">
        <tr>
            <td>
                <input type="text" ng-model="cnt.name">
                <input type="text" ng-model="cnt.val1">
                <input type="text" ng-model="cnt.val2">
                <input type="text" ng-model="cnt.val3()">
            </td>
        </tr>
    </table>
</div>

Open in new window

the function is not getting called in change of value in val1 or val2.

Any help would be appreciated.

Thanks.
Avatar of ambience
ambience
Flag of Pakistan image

Try

<input type="text" value="{{val3()}}" >

though it totally does not make sense to use an input for a calculated value. You cannot use ng-model on calculated fields since its not writable.
test page : https://jsfiddle.net/h24bwg4e/

var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl", ["$scope", function($scope) {
    $scope.dtArray = [
        { name:"John", val1:10, val2:20, val3:0 },
        { name:"Jane", val1:50, val2:200, val3:0 }
    ];
}]);

Open in new window

Hi replace the line <input type="text" value="{{val3()}}" /> to <input type="text" value="{{cnt.val1 + cnt.val2}}" />

in https://jsfiddle.net/h24bwg4e/
ASKER CERTIFIED SOLUTION
Avatar of BigRat
BigRat
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial