S
S
Sergey Nikolaev2015-05-26 16:29:25
JavaScript
Sergey Nikolaev, 2015-05-26 16:29:25

How to recalculate data on a page in Angular?

The user enters data into inputs.
In other inputs, you need to perform actions on the data and output, how to do it so that every time the data changes, a recalculation and output occurs? How to hang a handler on a form?
It doesn't work like that

<input value="{{Math.round(wh.price*wh.count/100)}}">

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2015-05-26
@Devastor

do it in the controller, not in the views, and in the views only ng-model and no formulas in the views.
example (the same method was suggested by @kirill-93)
Profit - you can conveniently and beautifully cover this matter with tests, everything is predictable, it is convenient to write, and the performance of such a solution is much better. Well, yes, as formulas become more complex, element dependencies, etc. it's much easier to sort it out.

M
Mikhail Osher, 2015-05-26
@miraage

DEMO .

angular.module('toster', [])

.controller('MainCtrl', function($scope) {
    $scope.data = {
        price: 0,
        count: 0
    };
    
    $scope.$watchCollection('data', function(data) {
        var computed = 0;
        
        var count = parseInt(data.count, 10);
        
        if (count) {
            computed = Math.round(data.price * count / 100);
        }
        
        $scope.computed = computed;
    });
});

S
Sergey Gavrilov, 2015-05-26
@FireVolkhov

<input ng-model="superModel">

scope.$watch("Math.round(wh.price*wh.count/100)", function(val){
    scope.superModel = val;
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question