AngularJS Example: Carrito Compra Refactor 2
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
<div data-ng-app="MiCarrito">
<div class="well container-fluid">
<pane title="Productos">
<div class="row" ng-controller="ProductosController">
<table class="table table-striped">
<thead>
<tr>
<th class="span1">Id</th>
<th class="span5">Producto</th>
<th class="span2">Cantidad</th>
<th class="span2">Precio</th>
<th class="span2">Total</th>
<td></td>
</tr>
</thead>
<tr class="well" ng-repeat="item in productos">
<td>{{item.Id}}</td>
<td>{{item.Producto}}</td>
<td>
<input type="text" ng-model="item.Cantidad" />
</td>
<td>{{item.Precio}}</td>
<td>{{ item.Precio|formatoMoneda}}</td>
</tr>
<tr class="well">
<td></td>
<td></td>
<td>Total</td>
<td></td>
<td>{{precioTotal()|formatoMoneda}}</td>
</tr>
</tbody>
</table>
</div>
</pane>
<pane title="Carrito">
<div class="row"...
CSS
html img{ width: 200px; height: 150px; }
JavaScript
var miCarrito = angular.module("MiCarrito", []);
miCarrito.controller(
'ProductosController',
['$scope','ProductosService', 'CarritoService',
function ($scope, prodService, carService) {
$scope.productos = [];
$scope.agregar = function (p) {
carService.agregar(p);
}
$scope.formatoMoneda = function(valor){
var valor = parseFloat(valor);
return "S/." + Math.floor(valor) + "." + (valor * 100) % 100;
}
prodService.listar(function(data){
$scope.productos = data;
});
}]);
miCarrito.controller(
'CarritoController', ['$scope', 'CarritoService',
function ($scope, carService) {
$scope.carrito = [];
/*carService.listar(function(data){
$scope.carrito = data;
});*/
carService.carrito = $scope.carrito;
$scope.precioTotal = function(){
var total = 0;
angular.forEach($scope.carrito, function(item){
total = total + (item.Cantidad * item.Producto.Precio);
});
return total;
};
$scope.eliminar = function(item){
carService.eliminar(item);
};
}]);
miCarrito.filter('formatoMoneda', function() {
return function(input) {
var out = "";
var valor = parseFloat(input);
out = "S/." + Math.floor(valor) + "." + ((valor * 100) % 100 + '00').substr(0,2);
return out;
}
});
miCarrito.factory('CarritoService', ['$http', function($http){
var servicio = {};
servicio.carrito = [];
var filtrar = function(id){
for (var i = 0; i < servicio.carrito.length; i++) {
if (servicio.carrito[i].Producto.Id == id) {
return servicio.carrito[i];
}
};
return null;
};
servicio.agregar = function(p){
var itemActual = filtrar(p.Id);
if (!itemActual) {
servicio.carrito.push({
Producto: p,
Cantidad: 1
...