Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a model property directly to a computed property of another model in AngularJS?

I'm just starting to create a small project with AngularJS.

Due to structural reasons, I'd like to decompose my model in several sub models like so:

var myCtrl = function ($scope) {

    $scope.mainModel = [
        {modelTitle:'learn angular', sum:0},
        {modelTitel:'build an angular app', sum:0}
    ];

    $scope.subModel1 = [
        {item:'learn angular', value:2},
        {item:'build an angular app', value:2}
    ];

    $scope.subModel2 = [
        {item:'learn angular', value:5},
        {item:'build an angular app', value:5}
    ];

}

Suppose, that the outcome of subModel1 and subModel2 is essential a sum of their item-values.

Thus, the sum of subModel1 is 4 and the sum of subModel2 is 10.

How do I bind programmatically mainModel[0].sum to the sum of subModel1 and likewise for subModel2?

Update: Just found AngularJS Fundamentals in 60-ish Minutes by Dan Wahlin. A beautiful introduction, which focusses on core concepts.

like image 613
SteAp Avatar asked Dec 07 '22 08:12

SteAp


1 Answers

If you only need the value in your view, you can define a function on $scope:

$scope.mainSum = function() {
    return $scope.subModel1[0].value + $scope.subModel2[0].value;
}

and then use it in your view:

<div>main sum = {{mainSum()}}</div>

If you need mainModel to be updated, do what @Tim already suggested in a comment -- use $watches in your controller:

$scope.$watch('subModel1[0].value', function(value) {
    $scope.mainSum[0].sum = value + $scope.subModel2[0].value;
});
$scope.$watch('subModel2[0].value', function(value) {
    $scope.mainSum[0].sum = $scope.subModel1[0].value + value;
});

Or you can watch the sum:

$scope.$watch(function() {
    return $scope.subModel1[0].value + $scope.subModel2[0].value;
 }, function(value) {
    $scope.mainSum[0].sum = value;
});
like image 160
Mark Rajcok Avatar answered Feb 09 '23 00:02

Mark Rajcok