How pass the selected ID from kendo combo box to angular function - angularjs

I am using a table and table body is in ng-repeat. I want to pass the ID of selected item through kendo combo box but it always pass the last item ID to the function.
<tbody>
<tr ng-repeat="hours in GetHours">
<td style="width:2%"><input type="checkbox" ng-model="hours.Selected" ng-change="RefreshSelectedDealsCount()" /></td>
<td style="width:25%;text-align:left">{{hours.ContactName}}</td>
<td style="width:25%;text-align:left">{{hours.Hours}}</td>
<td style="width:20%;text-align:left"><select id="combobox" kendo-combo-box class="form-control" k-ng-model="hours.DealName"
ng-click="GetDeals(hours)" k-options="myDealList" style="width: 190px" k-placeholder="'Select deal'"></select></td>
</tr>
</tbody>
//In JS controller->
//Get All the Deals Related to contacts
$scope.GetDeals = function (hours)
{
$scope.CurrentHour = hours;
}
// For Kendo Combo box in JS Controller
$scope.DealDataSource = {
serverFiltering: true,
transport: {
read: {
dataType: "json",
url: '/Project/GetContactDeals',
data: {
id: function () {
return $scope.CurrentHour.FKContactID;
},
},
}
}
};
$scope.myDealList = {
dataSource: $scope.DealDataSource,
dataTextField: "Todeal",
delay: 300,
autoBind:false,
highlightFirst: true,
select: function (ev) {
$scope.DelID = 0;
var dealID = this.dataItem(ev.item.index()).Dealid;
$scope.DelID = dealID;
$scope.CurrentHour.DealID = dealID
},
}

You can try with this code i think it is help you
<td style="width:20%;text-align:left"><select kendo-combo-box k-data-text-field="'Subject'" k-data-value-field="'DealID'" k-ng-model="hoursSelectedDeal" k-on-change="getSelectedContact(hoursSelectedDeal,kendoEvent)" k-data-source="hours.DealList" style="width: 190px" k-placeholder="'Select deal'"></select></td>
$scope.getSelectedContact = function (item,e) {
console.log(e.sender.$angular_scope.this.hours);
for (var i = 0; i < $scope.GetHours.length; i++) {
for (var j = 0; j < $scope.GetHours[i].DealList.length; j++) {
if ($scope.GetHours[i].DealList[j].DealID == item) {
$scope.selectedRow.DealID = $scope.GetHours[i].DealList[j].DealID;
$scope.selectedRow.DealName = $scope.GetHours[i].DealList[j].Subject;
$scope.selectedRow.ContactID = $scope.GetHours[i].FKContactID;
}
else
{
$scope.selectedRow.DealID = 0;
$scope.selectedRow.DealName = e.sender.$angular_scope.hoursSelectedDeal;
$scope.selectedRow.ContactID = e.sender.$angular_scope.this.hours.FKContactID;
}
}
}
var index = -1;
for (var k = 0; k < $scope.AllSelectedContacts.length; k++) {
if ($scope.AllSelectedContacts[k].ContactID == $scope.selectedRow.ContactID) {
if( $scope.AllSelectedContacts[k].DealID == $scope.selectedRow.DealID)
{
index = 1;
$scope.AllSelectedContacts.splice(k);
}
else
{
index = 1;
$scope.AllSelectedContacts[k].DealID = $scope.selectedRow.DealID;
$scope.AllSelectedContacts[k].DealName = $scope.selectedRow.DealName;
}
}
}
if (index == -1) {
$scope.AllSelectedContacts.push({
DealID: $scope.selectedRow.DealID,
DealName: $scope.selectedRow.DealName,
ContactID: $scope.selectedRow.ContactID
});
}
console.log($scope.selectedRow);
}

Related

knockout - header checkbox stays unchecked in table header when clicked

I am new to knockout and I am stuck at a problem for last couple of days - I am sure it is something silly but cant figure out. Any help will be appreciate.
I am trying to select and deselect all rows in a table based on the header check box column. The SelectAll function works and selects/unselects all rows in table but the header remains unckecked?
<tr>
<th><input type="checkbox" data-bind="click: selectAll, checked: AllChecked"></th>
<th>#Html.Vocab("Document")</th>
<th>#Html.Vocab("Notes")</th>
<th>#Html.Vocab("Created")</th>
</tr>
<tbody data-bind="foreach: DocumentRows">
<tr >
<td><input type="checkbox" data-bind="checked: IsSelected"></td>
<td><data-bind="text: Notes"></td>
</tr>
</tbody>
And here is the script:
//Document
class Document {
Id: KnockoutObservable<number>;
Notes: KnockoutObservable<string>;
IsSelected: KnockoutObservable<boolean>;
constructor(data?) {
this.Id = ko.observable(0);
this.Notes = ko.observable("").extend({ defaultValue: "" });
this.IsSelected = ko.observable(false);
if (data != null) {
ko.mapping.fromJS(data, {}, this);
}
}
};
//DocumentS VIEW MODEL
class DocumentsViewModel {
DocumentRows: KnockoutObservableArray<Document>;
IsAnySelected: KnockoutObservable<boolean>;//used for delete button
constructor(params) {
this.DocumentRows = ko.observableArray([]);
this.selectedIds = ko.observableArray([]);
}
InitComputed = () => {
this.AllChecked= ko.pureComputed({
read: function () {
return this.selectedIds().length === this.DocumentRows().length;
},
write: function (value) {
this.selectedIds(value ? this.DocumentRows.slice(0) : []);
},
owner: this
}
this.IsAnySelected = ko.pureComputed(() => {
var isChecked = false;
ko.utils.arrayForEach(this.DocumentRows(), function (item) {
if (item.IsSelected()) {
isChecked = true;
}
});
return isChecked;
});
}
selectAll = (): void => {
if (this.selectedIds().length > 0) {
this.selectedIds.removeAll();
ko.utils.arrayForEach(this.DocumentRows(), function (item) {
item.IsSelected(false);
});
} else {
ko.utils.arrayPushAll(this.selectedIds(), this.DocumentRows())
ko.utils.arrayForEach(this.DocumentRows(), function (item) {
item.IsSelected(true);
});
}
}
}

How to manipulate ngfor table, to toggle between two arrays

I would like to know if there is a simple way of parsing different array to a single *ngfor table. I have the below codes:
.html
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="radio" name="date" (click)="valid()" />
<label class="form-check-label">Valid</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="date" (click)="invalid()"/>
<label class="form-check-label">Invalid</label>
</div>
</div>
<tr *ngFor="let myAccount of Account | filterBy: accountFilter | paginate: { itemsPerPage: count, currentPage: p }; let i = index">
<td>{{ (p - 1) * count + i + 1 }}</td>
<td>{{myAccount.name}}</td>
<td>{{myAccount.startDate}}</td>
<td>{{myAccount.endDate}}</td>
</tr>
.ts
Account = [];
radioAccount = [];
currentDate = '';
ngOnInit() {
showAll();
}
showAll() {
return this.acctService.getAccount().subscribe(data => this.Account = data);
}
valid() {
this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
this.radioAccount = this.Account.filter(data => {
return data.startDate < this.currentDate && data.endDate > this.currentDate});
}
invalid() {
this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
this.radioAccount = this.Account.filter(data => {
return data.startDate < this.currentDate && data.endDate <= this.currentDate});
}
You can see that I have two arrays, how do I display content of "radioAccount" array when a radio button is clicked? That is, the possibility of swiching between "Account" content and "radioAccount" content. I don't think repeating the *ngfor code with *ngif is a solution.
You can create an array which will not be filtered, e.g., AccountSource and then you can assign original values (AccountSource) to Account:
Account = [];
AccountSource= [];
showAll() {
return this.acctService.getAccount()
.subscribe(data => {
this.Account = data;
this.AccountSource = data;
});
}
valid() {
this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
this.Account = this.Account.filter(data => {
return data.startDate < this.currentDate && data.endDate > this.currentDate});
}
invalid() {
this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
this.Account = this.Account.filter(data => {
return data.startDate < this.currentDate && data.endDate <= this.currentDate});
}
setSourceData() {
this.Account = this.AccountSource;
}
and call setSourceData() method whenever you want to see original values.

The ng-repeat array is updating table data for the first time i'm selecting value, but its not updating the table data only once

I'm trying to update the table view depending on select option. The table view is updating only once, when i select the option second time the view is not updating, I'm not getting what's the problem. please help me solve this..
here is app.js
$scope.User = {};
$scope.arr = [];
$scope.loaddata = function(User) {
$scope.User.site = layouts;
AllServices.teamAllDataFunction1(User)
.then(function(response) {
$scope.User.data=response.data;
});
};
$scope.getdatalayoutwise = function(User) {
var total = 0;
var total1 = 0;
for (var i = 0; i < ($scope.User.data).length; i++) {
if($scope.User.data[i].Layout == $scope.User.selectedSite) {
total += parseInt($scope.User.data[i].dp_inst_pending);
$scope.arr.push($scope.User.data[i]);
}
}
for (var j = 0; j < ($scope.User.data1).length; j++) {
if($scope.User.data1[j].Layout == $scope.User.selectedSite) {
total1 += parseInt($scope.User.data1[j].DP_Inst_Pending);
}
}
$scope.User.teamTotal = total;
$scope.User.personalTotal = total1;
$scope.data = [$scope.User.teamTotal, $scope.User.personalTotal];
$scope.totamnt = parseInt($scope.User.personalTotal) + parseInt($scope.User.teamTotal);
$scope.User.totalamount = $filter('translate')('totalpending') + ": " + $filter('currency')($scope.totamnt, "");
$scope.User.data = $scope.arr;
};
here is html
<select name="site" ng-model="User.selectedSite" ng-change="getdatalayoutwise(User)">
<option value="">--{{'selectsite_message' | translate}}--</option>
<option ng-repeat= "option in User.site" value="{{option.Layout}}">{{option.Layout}}</option>
</select>
<table ng-table>
<tr>
<th>advisor_name</th>
<th>totalpending</th>
</tr>
<tr ng-repeat="data in User.data | filter : {Layout: User.selectedSite}: true" ng-if="data.dp_inst_pending">
<td class="ui-helper-center"><a ng-click="advisorDetails($index, data, User)">{{data.AdvisorName}}</a></td>
<td>{{data.dp_inst_pending | currency:"₹":0}}</td>
</tr>
</table>
you need to use $scope.$apply() :
$scope.getdatalayoutwise = function(User) {
$scope.$apply(function () {
var total = 0;
var total1 = 0;
for (var i = 0; i < ($scope.User.data).length; i++) {
if($scope.User.data[i].Layout == $scope.User.selectedSite) {
total += parseInt($scope.User.data[i].dp_inst_pending);
$scope.arr.push($scope.User.data[i]);
}
}
...
});
}
https://www.grafikart.fr/formations/angularjs/apply-watch-digest
Change your function to this
$scope.loaddata = function(User) {
$scope.User.data = [];
$scope.User.site = layouts;
AllServices.teamAllDataFunction1(User)
.then(function(response) {
$scope.User.data=response.data;
});
and add a ng-if
<table ng-table ng-if="User.data.length">
<tr>
<th>advisor_name</th>
<th>totalpending</th>
</tr>
<tr ng-repeat="data in User.data | filter : {Layout: User.selectedSite}: true" ng-if="data.dp_inst_pending">
<td class="ui-helper-center"><a ng-click="advisorDetails($index, data, User)">{{data.AdvisorName}}</a></td>
<td>{{data.dp_inst_pending | currency:"₹":0}}</td>
</tr>
</table>
Add this as the first line in getdatalayoutwise () function:
$scope.arr = [];
got it working by just doing following
$scope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
$scope.getdatalayoutwise = function(User) {
var total = 0;
var total1 = 0;
for (var i = 0; i < ($scope.User.data).length; i++) {
if($scope.User.data[i].Layout == $scope.User.selectedSite) {
total += parseInt($scope.User.data[i].dp_inst_pending);
$scope.arr.push($scope.User.data[i]);
}
}
...
$scope.safeApply (function () {
$scope.User.data = $scope.arr;
});
};

Show unique items with count of duplicate occurrences in ng-repeat

I have a below JSON:
[{"brand":"abc"},{"brand":"xyz"},{"brand":"abc"},{"brand":"abc"},{"brand":"por"},{"brand":"xyz"}]
Using ng-repeat, How can I display like -
Brand Occurances
abc (3)
xyz (2)
por (1)
i.e. brand name (number of duplicate occurrences of same brand name)?
You can create a custom function which will be returning the count from the existing array with the repeatvie values (occurances)
Along with the filter to show the unique values from the JSON:
$scope.getCount = function(i) {
var iCount = iCount || 0;
for (var j = 0; j < $scope.brands.length; j++) {
if ($scope.brands[j].brand == i) {
iCount++;
}
}
return iCount;
}
AND a filter will look like this:
app.filter('unique', function() {
return function (arr, field) {
var o = {}, i, l = arr.length, r = [];
for(i=0; i<l;i+=1) {
o[arr[i][field]] = arr[i];
}
for(i in o) {
r.push(o[i]);
}
return r;
};
})
Working Plunkr
To get unique items from an array you could write a custom filter, in AngularJS filters are used to modify the data to be displayed to the user and in order to get the count of the duplicate items from an array you can write a function on the controller's scope and call it in the view.
Check the below code snippet on how to achieve it.
angular
.module('demo', [])
.controller('DefaultController', DefaultController)
.filter('unique', unique);
function DefaultController() {
var vm = this;
vm.items = [
{
"brand":"abc"
},
{
"brand":"xyz"
},
{
"brand":"abc"
},
{
"brand":"abc"
},
{
"brand":"por"
},
{
"brand":"xyz"
}
];
vm.getBrandCount = getBrandCount;
function getBrandCount(brand) {
var count = 0;
if (brand !== undefined && brand !== null && brand.length > 0) {
for (var i = 0; i < vm.items.length; i++) {
if (vm.items[i].brand === brand) {
count++;
}
}
}
return count;
}
}
function unique() {
return function(array, key) {
if (angular.isArray(array) && array.length > 0 && key !== undefined && key !== null && key.length > 0) {
var arr = [], keys = [];
for (var i = 0; i < array.length; i++) {
if (keys.indexOf(array[i][key]) === -1) {
keys.push(array[i][key]);
arr.push(array[i]);
}
}
return arr;
}
return array;
}
}
.brandcount:before {
content: '('
}
.brandcount:after {
content: ')'
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<table>
<thead>
<tr>
<th>Brand</th>
<th>Occurances</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in ctrl.items | unique: 'brand'">
<td>
<span ng-bind="item.brand"></span>
</td>
<td>
<span class="brandcount" ng-bind="ctrl.getBrandCount(item.brand)"></span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
You need to first process your data before passing to ng-repeat like this:
var app = angular.module("sa", []);
app.controller("FooController", function($scope) {
var data = [{
"brand": "abc"
}, {
"brand": "xyz"
}, {
"brand": "abc"
}, {
"brand": "abc"
}, {
"brand": "por"
}, {
"brand": "xyz"
}];
$scope.processedData = [];
// Group the raw data based on the brand name and store the count
function groupData() {
angular.forEach(data, function(item) {
// Check https://github.com/sagrawal14/angular-extras/blob/master/src/extras/array.js for this utility "find" method
var existingBrand = $scope.processedData.find("brand", item.brand);
if (!existingBrand) {
existingBrand = item;
existingBrand.count = 0;
$scope.processedData.push(existingBrand);
}
existingBrand.count++;
});
}
groupData();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://rawgit.com/sagrawal14/angular-extras/master/src/extras/array.js"></script>
<div ng-app="sa" ng-controller="FooController">
<table>
<tr ng-repeat="data in processedData">
<td>{{data.brand}}</td>
<td>{{data.count}}</td>
</tr>
</table>
<br><br>Processed/grouped data: {{processedData | json}}
</div>

Custom angular directive controller not updating

I created my own angular directive which can simply be used as:
<basket-summary></basket-summary>
This element is used on my master template page (the index.html).
The directive is as follows:
/* Directive */
angular.module('ecommerceDirectives').directive('basketSummary', [function() {
return {
restrict : 'E',
scope: {},
replace: true,
controller : 'BasketController',
controllerAs: 'basketController',
bindToController: {
basketController : '='
},
templateUrl: function(element, attrs) {
if (typeof attrs.templateUrl == 'undefined') {
return 'app/views/basket-summary.html';
} else {
return attrs.templateUrl;
}
},
link: function (scope, element, attrs) {
console.log("test");
}
};
}]);
The templateUrl of this directive is as follows:
<div class="btn-group pull-right">
<a class="btn btn-warning" ng-click="basketController.viewBasket()"><span class="badge">{{basketController.getTotalQuantities()}}</span> <span class="hidden-xs">Shopping</span> Cart</a>
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
<span class="fa fa-caret-down"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<div class="col-xs-12 cartItemHeader">
<h4>My Shopping Cart</h4>
</div>
<div class="quickCart" ng-repeat="cartItem in basketController.customerBasket.items">
<div class="col-xs-12 cartItemWrap">
<div class="col-xs-12 desc">{{cartItem.product.title}}</div>
<div class="col-xs-5 col-sm-8 price">{{cartItem.product.rrp_currency}} {{cartItem.product.rrp_amount}}</div>
<div class="col-xs-6 col-sm-3 units">Items: {{cartItem.quantity}}</div>
<div class="col-xs-1 trash"><a ng-click="basketController.deleteCartItem(cartItem.product.id)"><i class="fa fa-trash"></i></a></div>
</div>
</div>
</div>
And the BasketController is as follows:
/* Controller */
angular.module('ecommerceControllers').controller('BasketController', ['$rootScope', '$scope', '$route', '$location', 'CustomerBasketService', 'AppSettingService', 'StorageService', 'DEFAULT_CURRENCY_CODE', 'MERCHANT_ID_KEY', function($rootScope, $scope, $route, $location, CustomerBasketService, AppSettingService, StorageService, DEFAULT_CURRENCY_CODE, MERCHANT_ID_KEY) {
function basketProduct(product) {
this.id = product.id;
this.title = product.title;
this.categories = product.categories;
this.images = product.imaes;
this.created_on = product.created_on;
this.sku_code = product.sku_code;
this.lang = product.lang;
this.short_description = product.short_description;
this.attributes = product.attributes;
this.rrp_currency = product.rrp_currency;
this.rrp_amount = product.rrp_amount;
this.barcode_number = product.barcode_number;
this.last_modified_on = product.last_modified_on;
}
function basketItem(quantity, product) {
this.quantity = quantity;
this.product = new basketProduct(product);
}
function load() {
var basket = StorageService.get("customer_basket");
if (basket) {
for (var i = 0; i < basket.items.length; i++) {
var cartItem = basket.items[i];
cartItem = new basketItem(cartItem.quantity, cartItem.product);
basket.items[i] = cartItem;
}
}
return basket;
}
var basketController = this;
$scope.basketController = basketController;
basketController.customerBasket = load();
if (!basketController.customerBasket) {
basketController.customerBasket = {
shipping : null,
taxRate : null,
tax : null,
items : []
};
}
basketController.addCartItem = function(quantity, product) {
if (product == undefined || product == null) {
throw "No Product was specified.";
}
if (quantity == undefined || quantity == null) {
quantity = null;
}
var found = false;
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
if (product.id === cartItem.product.id) {
found = true;
cartItem.quantity = cartItem.quantity + quantity;
if (cartItem.quantity < 1) {
basketController.customerBasket.items.splice(i, 1);
} else {
$rootScope.$broadcast('customerBasketItemUpdated', {item: cartItem});
}
}
}
}
if (!found) {
var cartItem = new basketItem(quantity, product);
basketController.customerBasket.items.push(cartItem);
$rootScope.$broadcast('customerBasketItemAdded', {item: cartItem});
}
basketController.saveBasket();
}
basketController.updateBasket = function() {
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
if (cartItem.quantity < 1) {
basketController.customerBasket.items.splice(i, 1);
}
}
}
basketController.saveBasket();
}
basketController.deleteCartItem = function(productId) {
if (productId == undefined) {
throw "Product ID is required.";
}
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
if (productId == cartItem.product.id) {
basketController.customerBasket.items.splice(i, 1);
}
}
}
//Save
basketController.saveBasket();
}
basketController.getCurrencyCode = function() {
var code = DEFAULT_CURRENCY_CODE;
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
code = basketController.customerBasket.items[0].product.rrp_currency;
}
return code;
};
basketController.getTotalQuantities = function(id) {
var total = 0;
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
if (id == undefined || id == cartItem.product.id) {
total += cartItem.quantity;
}
}
}
return total;
};
basketController.getTotalAmount = function(cartItem) {
var total = 0;
if (cartItem) {
total = (cartItem.quantity * cartItem.product.rrp_amount);
}
return total.toFixed(2);
};
basketController.getFinalTotalAmount = function() {
var total = 0;
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
total += (cartItem.quantity * cartItem.product.rrp_amount);
}
}
return total.toFixed(2);
};
basketController.clearBasket = function() {
StorageService.set("customer_basket", null);
basketController.customerBasket = {
shipping : null,
taxRate : null,
tax : null,
items : []
};
$rootScope.$broadcast('customerBasketCleared', {});
}
basketController.saveBasket = function() {
if (basketController.customerBasket) {
StorageService.set("customer_basket", basketController.customerBasket);
$rootScope.$broadcast('customerBasketSaved', {});
}
}
basketController.checkout = function(serviceName, clearCart) {
if (serviceName == undefined || serviceName == null) {
serviceName = "PayPal";
}
switch (serviceName) {
case "PayPal":
basketController.checkoutPayPal(clearCart);
break;
default:
throw "Unknown checkout service '" + serviceName + "'.";
}
};
basketController.checkoutPayPal = function(clearCart) {
if (basketController.customerBasket && basketController.customerBasket.items && basketController.customerBasket.items.length > 0) {
// global data
var data = {
cmd: "_cart",
business: '', //parms.merchantID,
upload: "1",
rm: "2",
charset: "utf-8"
};
AppSettingService.getAppSetting(MERCHANT_ID_KEY).get().$promise
.then(function(result) {
data.business = result.value;
for (var i = 0; i < basketController.customerBasket.items.length; i++) {
var cartItem = basketController.customerBasket.items[i];
var ctr = i + 1;
data["item_number_" + ctr] = cartItem.product.sku_code;
data["item_name_" + ctr] = cartItem.product.title;
data["quantity_" + ctr] = cartItem.quantity;
data["amount_" + ctr] = cartItem.product.rrp_amount.toFixed(2);
}
// build form
var form = $('<form/></form>');
form.attr("action", "https://www.paypal.com/cgi-bin/webscr");
form.attr("method", "POST");
form.attr("style", "display:none;");
addFormFields(form, data);
$("body").append(form);
// submit form
form.submit();
form.remove();
if (clearCart) {
try {
basketController.clearBasket();
} catch (exception) {
}
}
}).catch(function(reason) {
console.log(reason);
});
}
};
basketController.viewBasket = function() {
$location.path("/basket");
$route.reload();
};
function addFormFields(form, data) {
if (data != null) {
$.each(data, function (name, value) {
if (value != null) {
var input = $("<input></input>").attr("type", "hidden").attr("name", name).val(value);
form.append(input);
}
});
}
}
return basketController;
}]);
My dilemma is as follows:
On my product page, I have product.html page (which is an angular view) and the "add to cart" button adds item to the cart but it doesn't update my cart summary button.
How do I make it that when I click the "add to cart" button that it update my cart and the number of items added to the cart?
The example image:
As you can see the orange button at the top right says that I have no items but there is 3 items in my cart already.
I tried various scoping allowed in directives but I seem to be failing to make it work.
PS: I am a newbie in AngularJS so please make your answer as simple to understand. :-)
The view product.html is linked to BasketController and this is the button that add item to cart.
<a class="btn btn-success btn-lg pull-right" role="button" ng-click="basketController.addCartItem(1, productController.selectedProduct)"><i class="fa fa-plus"></i> Add To Cart</a></div>
You have an isolated scope issue. The controller of your directive is not the same as the controller you want to use in your product page. See: scopes
I would suggest you to create a factory, which is always a singleton where you store your basket products and inject them in both, the directive and the products page

Resources