Krowar
Krowar

Reputation: 591

Alter scope data in a function

I'm developing an app with angular and I want to do some math on an object variable in an edit page.

For instance when I get my proposition (the object), I want to set proposition.marge_theorique like this proposition.marge_theorique= 2 * proposition.marge_grille at page load.

First thing I do is that I get the object with the API, and then I call my function calcul() that has to do the math.

My problem is that I don't know how to tell calcul to alter the $scope.proposition.

Here is my code

'use strict';

var app = angular.module('app', []);

app.controller('propositionCtrl',['$scope', 'propositionRepository', '$http',
    function ($scope, propositionRepository, $http) {
       // $scope.proposition = { marge_propose: 3 };



        //////////////////////////////DEFINITIONS////////////////////////////////////
        $scope.submit = function () {
            $http.put('/api/propositionapi', $scope.proposition);
        }




        function getProposition() {
            propositionRepository.getProposition(function (result) {
                $scope.proposition = result;

            }
            )
        }

        function calcul(contexte) {
           contexte.proposition.marge_theorique = contexte.proposition.marge_grille * 2;
        }

        ///////////////////////////////UTILISATION///////////////////////////////////
        console.log("on est dans la page");
        getProposition();
        calcul($scope);
;
    }])

app.factory('propositionRepository', function ($http) {
    return {
        getProposition: function (callback) {
            $http.get('/api/propositionapi/3').success(callback);
        }
    }
})

I've also tried to do it this way

        function calcul() {
           $scope.proposition.marge_theorique = $scope.proposition.marge_grille * 2;
        } 

and then just call calcul() but it does not work either...

What should I do?

Thanks a lot!

Upvotes: 0

Views: 68

Answers (1)

Chandermani
Chandermani

Reputation: 42669

The getProposition call is async in nature, you need to wait for the response to be available. You can use the callback. Update the getProposition function.

function getProposition() {
            propositionRepository.getProposition(function (result) {
                $scope.proposition = result;
                calcul($scope);
            })
        }

And remove the call calcul($scope); done after getProposition(); from the end of controller

Upvotes: 1

Related Questions