Shopping Cart Application Using AngularJs controller - angularjs

I'm doing a shopping cart with AngularJs, but I'm having trouble adding products to the shopping cart.
I think error is on my Controller:
My data.json:
{
"items": [
{
"product": {
"name": "Smartphone",
"price": {
"value": 3509.10,
}
}
},
{
"product": {
"name": "Lenovo ",
"price": {
"value": 2599.00,
}
}
}
]
}
my controller.js :
var app = angular.module("list", []);
app.controller("ListCtrl", ["$scope", "$http",
function($scope, $http) {
$scope.products = [];
$http({
method: 'GET',
url: 'data.json'
}).success(function(data) {
angular.forEach(data.items, function(item, index) {
$scope.products.push(item.product);
});
});
}
$scope.carts=[];
$scope.add_cart = function(product){
if(product){
$scope.carts.push({ p_name: product.name, p_valor:product.price.value,);
}
}
$scope.total = 0;
$scope.setTotals = function(cart){
if(cart){
$scope.total += cart.p_valor;
}
}
$scope.remove_cart = function(cart){
if(cart){
$scope.carts.splice($scope.carts.indexOf(cart), 1);
$scope.total -= cart.p_valor;
}
}
]);
my html:
<body ng-controller="ListCtrl" ng-app="list">
<ul ng-repeat="product in products">
<li>{{product.name}} </li>
<li>{{product.price.value}}</li>
<li><button type = "button" ng-click = "add_cart(product)"> Add to cart</button></li>
</ul><br>
<ul ng-repeat = "cart in carts" ng-init = "setTotals(cart)">
<li>{{cart.p_name}}</li>
<li>{{cart.p_price}}</li>
<li><button type = "button" ng-click = "remove_cart(cart)">X</button>
</li>
</ul>
<ul>
<li>{{total}}</li>
</ul>
</body>
I need the button add to cart to work correctly, bringing the product name and the value of the product. I also need it to bring the total value and also need to remove the product when clicking button remove cart.
Ty for Help guys!

your controller.js file contain some syntax error. please check for any typo or syntax error in code before you throw your code into stackoverflow 's basket. anyway,
there are some point you need to remember when code.
camelCase is recommended in javascript. as per conventions
each function should dedicated to perform a specific task (personal opinion)
it's good to follow styleguide angularjs &
javascript
$scope, and $watch is for data binding, so you can use data in template or in other scopes like directive. data-binding is great and primary selling point of AngularJs, but it has some drawbacks.
and power comes with great responsibility. :wink
please have a look, here is a working live demo of your code.
var app = angular.module("list", []);
ListController.$inject = ["$scope", "$http"];
app.controller("ListCtrl", ListController);
function ListController($scope, $http) {
function onLoad() {
$scope.products = [];
$scope.carts = [];
$scope.total = 0;
// getProducts();
demoData();
}
onLoad();
$scope.addCart = addCart;
$scope.getTotals = getTotals;
$scope.removeCart = removeCart;
// hould remove when using in prod
function demoData() {
var data = {
"items": [{
"product": {
"name": "Smartphone",
"price": {
"value": 3509.10,
}
}
},
{
"product": {
"name": "Lenovo ",
"price": {
"value": 2599.00,
}
}
}]
}
parseProducts(data.items);
}
function getProducts() {
$http.get('data.json')
.success(function(data) { parseProducts(data.items) })
}
function parseProducts(items) {
angular.forEach(items, function(item, index) {
$scope.products.push(item.product);
});
}
function addCart(product){
if(product){
$scope.carts.push({
p_name: product.name,
p_price:product.price.value
});
}
}
function getTotals(){
var initialValue = 0;
$scope.total = $scope.carts.reduce((x,y) => x + y["p_price"], initialValue);
}
function removeCart(i){
$scope.carts.splice(i, 1);
getTotals();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="list" ng-controller="ListCtrl">
<ul ng-repeat="product in products">
<li>{{product.name}} </li>
<li>{{product.price.value}}</li>
<li><button type = "button" ng-click = "addCart(product)"> Add to cart</button></li>
</ul><br>
<ul ng-repeat="cart in carts track by $index" ng-init = "getTotals(cart)">
<li>{{cart.p_name}}</li>
<li>{{cart.p_price}}</li>
<li><button type = "button" ng-click = "removeCart($index)">X</button>
</li>
</ul>
<ul>
<li>{{total}}</li>
</ul>
<button ng-click="getTotals()">get totals</button>
</body>

I found some Syntax error
var app = angular.module("list", []);
app.controller("ListCtrl", ["$scope", "$http",
function ($scope, $http) {
$scope.products = [];
$http({
method: 'GET',
url: 'data.json'
}).success(function (data) {
angular.forEach(data.items, function (item, index) {
$scope.products.push(item.product);
});
});
$scope.carts = [];
$scope.add_cart = function (product) {
if (product) {
$scope.carts.push({
p_name: product.name,
p_valor: product.price.value,
}); //Here syntax err
}
}
$scope.total = 0;
$scope.setTotals = function (cart) {
if (cart) {
$scope.total += cart.p_valor;
}
}
$scope.remove_cart = function (cart) {
if (cart) {
$scope.carts.splice($scope.carts.indexOf(cart), 1);
$scope.total -= cart.p_valor;
}
}
} //Here syntax err
]);

Related

won't remove automatically after it deleted from localstorage

First, here's the code
controller.js
.controller('FavoritesController', ['$scope', 'dishes', 'favorites', 'favoriteFactory', 'baseURL', '$ionicListDelegate', '$ionicPopup', '$ionicLoading', '$timeout', '$localStorage', function ($scope, dishes, favorites, favoriteFactory, baseURL, $ionicListDelegate, $ionicPopup, $ionicLoading, $timeout, $localStorage) {
$scope.baseURL = baseURL;
$scope.shouldShowDelete = false;
$scope.favorites = favorites;
$scope.dishes = dishes;
console.log($scope.dishes, $scope.favorites);
$scope.toggleDelete = function () {
$scope.shouldShowDelete = !$scope.shouldShowDelete;
console.log($scope.shouldShowDelete);
}
$scope.deleteFavorite = function (index) {
var confirmPopup = $ionicPopup.confirm({
title: 'Confirm Delete',
template: 'Are you sure you want to delete this item?'
});
confirmPopup.then(function (res) {
if (res) {
console.log('Ok to delete');
favoriteFactory.deleteFromFavorites(index);
var old_favorite = JSON.parse($localStorage.get('favorites'));
var leng = Object.keys(old_favorite).length;
for (var i = 0; i < leng; i++) {
if (Object.keys(old_favorite)[i] == index) {
console.log("Deleted from localstorage! " + Object.keys(old_favorite)[i]);
old_favorite.splice(old_favorite.indexOf(index), 1);
$localStorage.storeObject('favorites', old_favorite);
}
}
} else {
console.log('Canceled delete');
}
});
$scope.shouldShowDelete = false;
}
}])
services.js
.factory('favoriteFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
var favFac = {};
var favorites = [];
favFac.addToFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
favorites.push({id: index});
};
favFac.deleteFromFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
favorites.splice(i, 1);
console.log("Deleted !" + index);
}
}
}
favFac.getFavorites = function () {
return favorites;
};
return favFac;
}])
favorites.html
<ion-view view-title="My Favorites">
<ion-nav-buttons side="secondary">
<div class="buttons">
<button class="button button-icon icon ion-ios-minus-outline"
ng-click="toggleDelete()"></button>
</div>
</ion-nav-buttons>
<ion-content>
<ion-list show-delete="shouldShowDelete">
<ion-item ng-repeat="dish in dishes | favoriteFilter:favorites" href="#/app/menu/{{dish.id}}" class="item-thumbnail-left" on-swipe-left="deleteFavorite(dish.id)">
<img ng-src="{{baseURL+dish.image}}" on-swipe-left="deleteFavorite(dish.id)">
<h2>{{dish.name}}
<span style="font-size:75%">{{dish.price | currency}}</span>
<span class="badge badge-assertive">{{dish.label}}</span></h2>
<p>{{dish.description}}</p>
<ion-delete-button class="ion-minus-circled"
ng-click="deleteFavorite(dish.id)">
</ion-delete-button>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
app.js
.state('app.favorites', {
url: '/favorites',
views: {
'mainContent': {
templateUrl: 'templates/favorites.html',
controller:'FavoritesController',
resolve: {
dishes: ['menuFactory', function(menuFactory){
return menuFactory.query();
}],
favorites: ['favoriteFactory', function(favoriteFactory) {
return favoriteFactory.getFavorites();
}]
}
}
}
})
So, after I attempt to use the deleteFavorite Function from the controller.js and the index inside the localstorage was success deleted, the data on the favorites.html couldn't updated, it couldn't deleted from the favorties.html immediately.
I need to refresh my browser first to show the up-to-date list based on the localstorage.
I hope that I can show the up-to-date data based on the localstorage data without refresh the page.
Did I make something wrong on here?
Thank you in advance!

angularjs ng-repeat filter on static value not working

I can't figure out why the code below is not filtering just the values with unique_id of "027". I've tried it as a string as well '027'...
JSON file:
[
{
"unique_id":"027",
"title":"How Speed Relates to Energy",
"state":"NY",
"state_id":"1.S2.3a"
}
]
Here my controller:
var abApp = angular.module('abApp', []);
abApp.factory('abData', function($http, $q) {
var deffered = $q.defer();
var data = [];
var abData = {};
abData.async = function() {
$http.get('/data/ab_activities.json')
.success(function(ab) {
data = ab;
deffered.resolve();
});
return deffered.promise;
};
abData.data = function() {
return data;
};
return abData;
});
abApp.controller("abEE", function(abData, $scope) {
var abApp = this;
abData.async().then(function(ab) {
abApp.alignments = abData.data();
});
})
Here's my HTML:
<div ng-controller="abEE as ee">
<ul>
<li ng-repeat="align in ee.alignments | filter:{unique_id : 027} ">
{{align.unique_id}} - {{align.state}}, {{align.state_id}}
</li>
</ul>
</div>
you need to correct your html markup like this, as in your JSON unique_id is a string:
<div ng-controller="abEE as ee">
<ul>
<li ng-repeat="align in ee.alignments | filter:{unique_id : '027'} ">
{{align.unique_id}} - {{align.state}}, {{align.state_id}}
</li>
</ul>

Multiple custom filters in angular.js

I have a multi check box application which requires me to have multiple filters. I have been unable to use multiple filters even if I try to hard code an array to filter on. Here is an example I have created to try to make this work.
Working Example
HTML MARKUP:
<body ng-app="app">
<div ng-controller="MainCtrl">
<div ng-repeat="item in data.sessions | IndustryFilter : data.sessions.industry ">
{{item.id}}
</div>
</div>
Javascript
var app = angular.module("app", [])
.controller("MainCtrl", function ($scope, MatchedFilterList) {
$scope.data = {"sessions": [{
"id": "a093000000Vhzg7AAB",
"industry": ["Automovtive"],
"sessionName": "Keynote",
},
{
"id": "a093000000zg7AAB",
"industry": ["Automovtive", "Retail"],
"sessionName": "Keynote2",
},
{
"id": "a093er000f00zg7AAB",
"industry": ["Automovtive", "Retail", "Consumer Goods"],
"sessionName": "Keynote3",
}
]};
}).filter("IndustryFilter", function (MatchedFilterList) {
return function () {
var filtered = [];
angular.forEach(MatchedFilterList.industry, function (item) {
filtered.push(item);
});
console.log("Filter: Filter " + filtered)
return filtered;
};
})
.factory("MatchedFilterList", function(){
var matchedFilterList = {};
matchedFilterList.industry = {
"Automotive": "Automotive",
"Retail" : "Retail"
};
return matchedFilterList;
});

Single Controller for multiple html section and data from ajax request angularjs

I'm trying to show two section of my html page with same json data, i don't want to wrap both in same controller as it is positioned in different areas. I have implemented that concept successfully by using local json data in "angular service" see the demo
<div ng-app="testApp">
<div ng-controller="nameCtrl">
Add New
Remove First
<ul id="first" class="navigation">
<li ng-repeat="myname in mynames">{{myname.name}}</li>
</ul>
</div>
<div>
Lot of things in between
</div>
<ul id="second" class="popup" ng-controller="nameCtrl">
<li ng-repeat="myname in mynames">{{myname.name}}</li>
</ul>
JS
var testApp = angular.module('testApp', []);
testApp.service('nameService', function($http) {
var me = this;
me.mynames = [
{
"name": "Funny1"
},
{
"name": "Funny2"
},
{
"name": "Funny3"
},
{
"name": "Funny4"
}
];
//How to do
/*this.getNavTools = function(){
return $http.get('http://localhost/data/name.json').then(function(result) {
me.mynames = result.mynames;
return result.data;
});
};*/
this.addName = function() {
me.mynames.push({
"name": "New Name"
});
};
this.removeName = function() {
me.mynames.pop();
};
});
testApp.controller('nameCtrl', function ($scope, nameService) {
$scope.mynames = nameService.mynames;
$scope.$watch(
function(){ return nameService },
function(newVal) {
$scope.mynames = newVal.mynames;
}
)
$scope.addName = function() {
nameService.addName();
}
$scope.removeName = function() {
nameService.removeName();
}
});
jsfiddle
Next thing i want to do is to make a http request to json file and load my two section with data, and if i add or remove it should reflect in both areas.
Any pointers or exisisitng demo will be much helpful.
Thanks
The reason why only one ngRepeat is updating is because they are bound to two different arrays.
How could it happen? It's because that you have called getNavTools() twice, and in each call, you have replaced mynames with a new array! Eventually, the addName() and removeName() are working on the last assigned array of mynames, so you're seeing the problem.
I have the fix for you:
testApp.service('nameService', function($http) {
var me = this;
me.mynames = []; // me.mynames should not be replaced by new result
this.getNavTools = function(){
return $http.post('/echo/json/', { data: data }).then(function(result) {
var myname_json = JSON.parse(result.config.data.data.json);
angular.copy(myname_json, me.mynames); // update mynames, not replace it
return me.mynames;
});
};
this.addName = function() {
me.mynames.push({
"name": "New Name"
});
};
this.removeName = function() {
me.mynames.pop();
};
});
testApp.controller('nameCtrl', function ($scope, nameService) {
// $scope.mynames = nameService.mynames; // remove, not needed
nameService.getNavTools().then(function() {
$scope.mynames = nameService.mynames;
});
/* Remove, not needed
$scope.$watch(
function(){ return nameService },
function(newVal) {
$scope.mynames = newVal.mynames;
}
);
*/
$scope.addName = function() {
nameService.addName();
};
$scope.removeName = function() {
nameService.removeName();
};
});
http://jsfiddle.net/z6fEf/9/
What you can do is to put the data in a parent scope (maybe in $rootScope) it will trigger the both views ,And you don't need to $watch here..
$rootScope.mynames = nameService.mynames;
See the jsFiddle

Angularjs displaying json in Rails

I am trying to display a list of my donors - the html is:
<div class="panel">
<header>
<h1> Donor Information </h1>
</header>
<div class="content">
<div ng-app="Donor">
<div ng-controller="DonorCtrl">
<ul>
<li ng-repeat="donor in donors">{{donors.name_last | json}}</li>
</ul>
</div>
</div>
</div>
</div>
My Donor_controller.js is this:
var app;
app = angular.module("Donor", ["ngResource"]);
app.factory("Donors", [
"$resource", function($resource) {
return $resource("/donors", {}, {
update: {
method: "PUT"
}
});
}
]);
app.factory("Donor", [
"$resource", function($resource) {
return $resource("/donors/:id", {
id: "#id"
}, {
update: {
method: "GET"
}
});
}
]);
this.DonorCtrl = [
"$scope", "Donor", "Donors", function($scope, Donor, Donors) {
var donor;
$scope.donor = Donor.query();
$scope.donors = Donors;
$scope.addDonor = function() {};
donor = Donor.save($scope.newDonor)(function() {
return $scope.donors.push(donor);
});
return $scope.newDonor = {};
}
];
I am returning from my rails app via donors/1.json this:
{
"donor": {
"id": 1,
"tools_id": null,
"first_name": "Billy",
"last_name": "Bullard"
}
}
I get a list of dots when I view and it shows this on inspection (repeated):
<li ng-repeat="donor in donors" class="ng-scope ng-binding"></li>
How do I go from the json coming from Rails to the list of names in Angularjs?
You should remove | json from your bind and you want the donor's lastname, not the donors':
<li ng-repeat="donor in donors">{{donor.name_last}}</li>
Update 1
Also, you should have $scope.donors = Donors.query(); in your controller, not $scope.donor = ....

Resources