jgonyer
jgonyer

Reputation: 121

Create an array of computed values that are bound to other inputs in AngularJS

I have two sets of inputs, each bound to values in arrays. Each array create the edges of a grid, the intersections of the grid will represent some calculation of the two inputs that define the intersection. Let's say aArr is the rows and bArr is the columns.

$scope.aArr = [{val: 1},{val: 1},{val: 1}];
$scope.bArr = [{val: 1},{val: 1},{val: 1}];

Can I create an array of intersections where each intersection updates whenever each defining value is update and then use that array with ng-repeat to create the markup?

Something like

$scope.intersections = [{val: $scope.aArr[0].val + $scope.bArr[0]}...]

gives me intersections that don't update and whenever I try to define interection[n].val as a function I get errors.

Edit

Seems I can define

$scope.intersections = [
  [function(){return $scope.aArr[0] + $scope.bArr[0]}, function(){return $scope.aArr[0] +         $scope.bArr[1]} ... ],
  [...],
  [...]
];

But I can't define an empty array then populate it programatically. Firebug throws something that looks like Error:[$interpolate:interr]...

Any thoughts?

Upvotes: 1

Views: 334

Answers (1)

Hassan Siddique
Hassan Siddique

Reputation: 1590

If you want some calculations when an object or value of an object changes then use the WATCH function.

See this fiddle for an example: http://jsfiddle.net/imhassan66/x6QaY/

In this example, I am adding the 1st value of both arrays. If you change these values it will update the SUM.

app.controller('MainCtrl', function ($scope) {

$scope.aArr = [{
        val: 1
    }, {
        val: 2
    }];

    $scope.bArr = [{
        val: 3
    }, {
        val: 43
    }];

    $scope.$watch("aArr", function () {
        $scope.doWorkInArrayChange();
    }, true);

    $scope.$watch("bArr", function () {
        $scope.doWorkInArrayChange();
    }, true);

    $scope.sum = "";
    $scope.doWorkInArrayChange = function () {
        $scope.sum = parseInt($scope.aArr[0].val) + parseInt($scope.bArr[0].val);
    };

Upvotes: 3

Related Questions