I'm quite new to Angular. I created a factory in order to reuse some functions across several controllers. This FIDDLE is a simpler version of my code, which doesn't work.
JS:
var AppModule = angular.module('myApp', []);
AppModule.factory('AppService', function(){
return{
convert: function convert(unit, value){
if (unit === '/day') {
cost = value*12/365;
}
else if (unit === '/month') {
cost = value;
}
else if (unit === '/year') {
cost = value*365;
}
return cost;
},
convert_all: function convert_all(selected_unit, costs){
converted_costs = angular.copy(costs);
angular.forEach(costs,function(cost, key){
converted_costs[key].value = convert(selected_unit, cost.value);
});
return converted_costs;
}
}
});
AppModule.controller('AppCtrl', function($scope, AppService){
$scope.units = ['/day', '/month', '/year'];
$scope.selected_unit = $scope.units[1];
$scope.costs = [{title:'Rent', value:800},{title:'Food', value:400}];
$scope.converted_costs = AppService.convert_all($scope.selected_unit, $scope.costs);
});
HTML:
<div ng-app="myApp">
<div ng-controller="AppCtrl">
<select ng-model="selected_unit" ng-options="selected_unit for selected_unit in units"></select>
<div ng-repeat="cost in converted_costs">
<p>{{cost.title}}: {{cost.value | currency}}</p>
</div>
</div>
</div>
The purpose is to be able to select a unit and have the costs converted automatically.
I think I have a first issue (probably wrong syntax) with my call to convert from convert_all, couldn't find out why.
And if I test with the convert function only on a single cost I get the conversion to work but only on the first instance. i.e. it won't update when another unit is selected. I understood that this is because the factory is singleton and doesn't watch for the changes in the selected unit. I read that I could emit the factory result to rootScope or broadcast the controller scopes, or maybe use promises but I couldn't get any of these solutions to work on my code and couldn't find a clear answer on the best way to deal with that.
Any idea or recommendation would be greatly appreciated.
thx