0

I have an array declared in the factory with the name "voci", then i have a controller that update the array with a function "CalcolaTotaleEuroPagine", what i want is to access to the array "voci" updated and print in the view, but it don't work. Herewhat i have done:

JS

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

//SERVICE THAT RETURN ARRAY
LandingApp.factory('PreventivoTotaleFront', function () {
   var voci = {};
   voci.lista = [];

   return {
      add: function (voce) {
         voci.lista.push({
            id: voci.lista.length,
            costo: voce
         });
        console.log(voci);
     }
   };
   return voci;
});


//CONTROLLER THAT UPDATE ARRAY
LandingApp.controller('numberpages',function($scope,PreventivoTotaleFront){

   $scope.primapagina = 150;
   $scope.altrepagine = 90;
   $scope.numeroaltrepagine = 0;
   $scope.TotaleEuroPagine = 0;

   $scope.CalcolaTotaleEuroPagine = function(){
       return $scope.TotaleEuroPagine = $scope.altrepagine * $scope.numeroaltrepagine + $scope.primapagina;
       PreventivoTotaleFront.add(TotaleEuroPagine);
   };

}); 

HTML

<body ng-app="LandingApp">
    <div class="container">

        <form ng-controller="numberpages">

            <label>N° Pagine interne: </label><input type="number" min="0" ng-model="numeroaltrepagine" ng-change="CalcolaTotaleEuroPagine()"></input>
            <br/>{{TotaleEuroPagine | currency:""}}€<br/>

             <!--PRINT THE ARRAY VOCI-->
            <div>{{voci}}</div>
        </form>

    </div>
</body>

1 Answer 1

0

There is misorder of statement

$scope.CalcolaTotaleEuroPagine = function(){
return $scope.TotaleEuroPagine = $scope.altrepagine * $scope.numeroaltrepagine + $scope.primapagina;
PreventivoTotaleFront.add(TotaleEuroPagine);
};

you returned from the function before calling the factory. Hence the factory does not update the array. Put PreventivoTotaleFront.add(TotaleEuroPagine); this line before return statement

Sign up to request clarification or add additional context in comments.

6 Comments

Now it return TypeError: dbg is undefined in the console.log
$scope.TotaleEuroPagine = $scope.altrepagine * $scope.numeroaltrepagine + $scope.primapagina; PreventivoTotaleFront.add(TotaleEuroPagine); return $scope.TotaleEuroPagine;
Now it works, but it don't print the array {{voci}} out in the view
i think you are directly trying to access the service variable. Access it through controller. As $scope.vociArr = PreventivoTotaleFront(); add this line in your controller. And in the view {{vociArr}}
hmm, thank you but i was trying a way to update factory data to share between more controllers
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.