how to refresh counter value of one controller from another angularjs - javascript

I have a cart counter which is in header controller. and a add to cart button which is in image view controller. I want to set cart counter from the image view controller. SO every time add to cart is clicked it changes the cart value.
Header controller :
decorpotCtrls.controller('DecorpotCtrl', [ '$scope', '$routeParams', 'cart',
function($scope, $routeParams, cart) {
$scope.cartCounter = cart.getCartCounter();
} ]);
Image Controller : -
decorpotCtrls.controller('ImageViewController', [
'$scope',
'$routeParams',
'imageView',
'$auth',
'cart',
function($scope, $routeParams, imageView, $auth, cart) {
$scope.addToCart = function(groupid) {
console.log($auth.isAuthenticated());
return cart.addToCart(groupid);
};
} ]);
cart Html : -
<i class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></i> Cart({{cartCounter}})
add to cart from image controller -
<div id="addToCart" class="btn btn-primary btn-lg buyNCartButton" ng-click="addToCart(groupid)">Add To Cart</div>
cart service -
services.service('cart', function($http){
var counter =0 ;
sessionStorage.setItem('cartCounter', counter);
//var
return {
checkout : function(){
},
addToCart : function(gruopid){
counter++;
return counter;
},
getCartCounter : function(){
return counter;
}
};
});

You could do one thing set method reference to $scope.cartCounter like
$scope.cartCounter = cart.getCartCounter;
Then on HTML you could call that method like cartCounter() that will get evaluated on each digest.
<i class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></i>
Cart({{cartCounter()}})

Use $rootScope in controller. All $scopes are "childs" of $rootScope.
decorpotCtrls.controller('ImageViewController', [
'$rootScope',
'$scope',
'$routeParams',
'imageView',
'$auth',
'cart',
function($scope,$rootScope, $routeParams, imageView, $auth, cart) {
$scope.addToCart = function(groupid) {
$rootScope.counter++;
console.log($auth.isAuthenticated());
return cart.addToCart(groupid);
};
} ]);

Related

AngularJs Table not updated after Create/Delete/update

If I Create/Update/Delete Values in my Array the ng-table is not Updating the Data. I need to do a window.location.reload() for that but thats not very "beautifull". Shouldnt in Angularjs through 2Way DataBinding and Automatic $apply Cycle it do it by it self?
My Code to Review maybe I forgot something:
'use strict';
(function() {
class TranslationsComponent {
constructor($http, $scope, $uibModal) {
this.$http = $http;
this.$scope = $scope;
this.$uibModal = $uibModal;
this.langV = [];
}
$onInit() {// getting my Datas
this.$http.get('/api/dict_keys/all/' + 1 + '/' + 1)
.then(response => {
this.langV = response.data;
});
}
// For Example Deleting something with a Modal
// Delete Modal
deleteKey(selectedKey) {
this.$uibModal.open({
scope: this.$scope,
templateUrl: 'delete.html',
controller: ['$scope', '$uibModalInstance', '$http', 'selectedKey',
function($scope, $uibModalInstance, $http) {
$scope.selectedKey = selectedKey;
this.$http = $http;
$scope.close = function() {
$uibModalInstance.dismiss();
};
$scope.delete = () => {
this.$http.delete('/api/dict_keys/' + selectedKey._id)
.then(() => {
//window.location.reload();
//what can i instead of realod do?
toastr.success('The Key is successfully Deleted');
$uibModalInstance.close();
});
};
}
],
resolve: {
selectedKey: () => selectedKey
}
});
}
/* ----------------------------------------- */
angular.module('euconDictionaryApp')
.component('translations', {
templateUrl: 'app/translations/translations.html',
controller: TranslationsComponent
});
})();
In my .html its a Simple ng-repeat showing everything, in short:
<tr dir-paginate="v in $ctrl.langV |itemsPerPage: 10">
<td>
{{v.Name}}
</td>
<td>
<!-- Delete Key Button -->
<button type="button" class="btn btn-default" ng-click="$ctrl.deleteKey(v)">
</button>
</td>
Looks like you will need to update 'this.langV' array after delete or update in order to see the update. You can use javascript splice method to remove an item from array.
After delete you can use
this.langV.splice(this.langV.indexOf(v), 1)
After update you can update the item like
this.langV[index] = updateItem

TypeError: $location.path is not a function

<span class="button-icon pull-left" ><i class="ti ti-plus" ng-click="itemOpen()"></i></span>
This is my Html Code.
$scope.itemOpen=function()
{
return $location.path('/ConsultationParameterMaster');
};
This is my script.
And the error is.
$location.path is not a function
You need to inject $location in your controller if you are going to do this. where you are missing 'focus' as a parameter
app.controller('sampleController', ['$scope','$http','$location', function($scope,$http,$location) {
$scope.itemOpen=function()
{
return $location.path('/ConsultationParameterMaster');
};
}
EDIT:
According to your comment,You need to arrange the dependencies,
coreModule.registerController('MedicalRecordsController', ['$rootScope', '$scope', '$sessionStorage', 'Restangular', '$element', '$themeModule', '$filter', '$uibModal', 'gettext', 'focus', '$location', function ($rootScope, $scope, $sessionStorage, Restangular, $element, $themeModule, $filter, $uibModal, gettext,focus,$location)
app.controller('ctrl', ['$http','$scope','$location', function($http,$scope,$location) {
$scope.itemOpen=function()
{
return $location.path('/ConsultationParameterMaster');
};
}
<span class="button-icon pull-left" ><i class="ti ti-plus" ng-click="itemOpen()"></i></span>
Your controller should take $location as an argument. If you forgot to inject $location, you obviously can't use it.
in your javascript, whereever your angular controller is defined, you need to inject dependency for $location, like this:
app.controller('myCtrl', ['$scope', '$location', function($scope, $location) {
...
}
Your dependencies aren't lined up correctly. You have 'focus' in the dependency list but not in the parameter list, so your $location is actually focus. That's why it doesn't have a .path() method.
To fix, add focus to your parameters:
$modal, gettext, /*-->*/focus/*<--*/, $location)

Information doesn't refresh after clicking on link in AngularJS. I've got {{ value }} but not the data

I have an Angular app that takes information from few JSON files.
The first JSON file contains data about cities and managers. Like this:
[
{
"link" : "veliky_novgorod",
"city" : "Великий Новгород",
"manager" : "mr. Sminth",
},
{
"link" : "magnitogorsk",
"city" : "Магнитогорск",
"manager" : "mr. Young",
},...
I use it in order to create a page for every city.
My urls look like this: ...index.html#/cities/veliky_novgorod/, ...index.html#/cities/biisk/, ...index.html#/cities/biisk/mobile/, etc.
Everything works fine, but when I try to go from one page to another information from the other JSON (scopes) doesn't load. After changing page I've always got {{ value }}
But when I make refresh manually, everything is going back to normal.
In other words, how can I reload new page after clicking on link. I tried to use window.location.reload() But it doesn't work.
<li ng-repeat="city in cities">
{{city.manager}}
</li>
My module and controller below:
var curryApp = angular.module('CurryApp', [
'ngRoute',
'curryControllers'
]);
curryApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'link_list.html',
controller: 'CurryListCtrl'
}).
when('/cities/:cityId/', {
templateUrl: 'template-total.html',
controller: 'CurryDetailCtrl'
}).
when('/cities/:cityId/mobile/', {
templateUrl: 'template-mobile.html',
controller: 'CurryMobileCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
That's my controller:
var curryControllers = angular.module('curryControllers', []);
curryControllers.controller('CurryListCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('cities.json').success(function(data) {
$scope.cities = data;
});
}]);
curryControllers.controller('CurryDetailCtrl', ['$scope', '$routeParams', '$http', '$route',
function($scope, $routeParams, $http, $route) {
$scope.reloadRoute = function(){window.location.reload();}
$scope.cityId = $routeParams.cityId;
$http.get('cities.json').success(function(data) {
$scope.cities = data;
$http.get('paidbc.json').success(function(data2) {
$scope.paidBc = data2;
$scope.isActive = function(item) {
return item.link === $scope.cityId;
};
});
});
}]);
curryControllers.controller('CurryMobileCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.cityId = $routeParams.cityId;
}]);
It seems that is an error related with the href attribute. According to docs:
The wrong way to write it:
link1
The correct way to write it:
<a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
In your case, use:
<a ng-href="#/cities/{{city.link}}" ng-click="reloadRoute()">{{city.manager}}</a>
instead of using only href.

indexOf deletes the wrong item in AngularJS

I am building a note taking application (something like a blog actually with different terms like post=note etc.) to practise my skills in AngularJS and Rails.
There is a sidebar on the left (controller Sidebar.js) which fetches all items form the Rails API and ng-repeats them to a list.
By clicking on one of them, the show.html renders inside ng-show on the right. The show view, has a link that lets you delete the item and then splices it from the sidebar on the left. After much blood, sweat and tears I believe I made it, except one detail: After deletion(=> destroy()) of the item, the wrong index gets deleted from the sidebar. I've tried to make it work with indexOf and then I console.logged the index - it always appears to be -1.
To share the same array of note objects I created a service that does that with a getter and a setter.
How can I delete the right item from the sidebar?
show.html
<div class="row">
<div class="col-lg-10">
<h3>{{ note.title }}</h3>
</div>
<div class="col-lg-2">
<button type="button" ng-click="destroy(note)" class="btn btn-default btn-xs pull-right">
<span class="glyphicon glyphicon-remove"></span></button>
</div>
</div>
<hr/>
<div class="note-description">
{{ note.description }}
<br>
</div>
Sidebar.js
var app = angular.module('notepadApp');
app.controller('SidebarController',
['$scope', '$http', '$routeParams', '$location', 'Note', 'ShareNoteScope',
function($scope, $http, $routeParams, $location, Note, ShareNoteScope) {
$scope.notes = Note.query(function (){
ShareNoteScope.setScope($scope.notes);
});
$scope.getClass = function (path) {
if ($location.path().substr(0, path.length) === path) {
return 'active';
} else {
return '';
}
}
}]
);
sidebar.html
<ul class="nav nav-stacked" ng-controller="SidebarController">
<li ng-repeat="note in notes.notes | orderBy: '-created_at'" class="note-li">
<a href="/notes/{{note.id}}" ng-class="getClass('/notes/{{note.id}}')"
class="" >
{{ note.title }}
</a>
<div ng-repeat="tag in note.tags">
<div class="label">{{ tag }}</div>
</div>
</li>
</ul>
NoteCtrl.js
'use strict';
var app = angular.module('notepadApp');
app.controller('NoteController',
['$scope', '$http', '$routeParams', '$location',
function($scope, $http, $routeParams, $location) {
}]
);
app.controller('NoteShowController',
['$scope', '$http', '$routeParams', '$location', 'Note', 'ShareNoteScope',
function($scope, $http, $routeParams, $location, Note, ShareNoteScope) {
if ($routeParams.id) {
Note.get({id: $routeParams.id}, function(note){
$scope.note = note.note;
});
}
else {
$scope.note = ShareNoteScope.getScope().notes[0].id;
}
//Destroy method for deleting a note
$scope.destroy = function(note) {
Note.remove({id: note.id}, function() {
var index = ShareNoteScope.getScope().notes.indexOf(note);
console.log(index);
ShareNoteScope.getScope().notes.splice(index, 1);
});
$location.path('/notes');
}
}]
);
app.controller('NoteCreateController',
['$scope', 'Note', '$routeParams', '$location','ShareNoteScope',
function($scope, Note, $routeParams, $location, ShareNoteScope) {
$scope.notes = ShareNoteScope.getScope().notes;
$scope.newNote = {};
$scope.createNote = function() {
Note.create($scope.note, function (newNote) {
$scope.notes.unshift(newNote.note);
$scope.newNote = '';
$scope.errors = '';
$location.path('/notes/'+newNote.note.id);
});
}
}]);
models.js
'use strict';
var app = angular.module('notepadApp');
app.factory('Note', ['$resource', function($resource) {
return $resource('/api/notes/:id', { id: "#id" }, {
get: {
method: 'GET'
},
query: {
method: 'GET',
isArray: false
},
create: {
method: 'POST'
}
});
}]);
app.factory('ShareNoteScope', function (Note) {
var $scope;
return {
setScope: function (scope) {
$scope = scope;
},
getScope: function () {
return $scope;
}
}
});
ShareNoteScope.getScope().notes contents
$$hashKey
"object:5"
created_at
"2015-11-29T09:07:18.614Z"
description
null
id
130
tags
[]
title
"5345"
updated_at
"2015-11-29T09:07:18.614Z"
user_id
1
We went to the bottom of this in the chat. And the problem probably had to do with note not referencing an object in ShareNoteScope.getScope().notes. So to get a correct reference, we used filter in this case:
JavaScript
$scope.destroy = function(note) {
Note.remove({id: note.id}, function() {
var res = ShareNoteScope.getScope().notes.filter(function(el){
return el.id == note.id;
});
note = res[0];
var index = ShareNoteScope.getScope().notes.indexOf(note);
console.log(index);
ShareNoteScope.getScope().notes.splice(index, 1);
});
$location.path('/notes');
}
Pass $index in destroy method along with note object
<div class="row">
<div class="col-lg-10">
<h3>{{ note.title }}</h3>
</div>
<div class="col-lg-2">
<button type="button" ng-click="destroy(note,$index)" class="btn btn-default btn-xs pull-right">
<span class="glyphicon glyphicon-remove"></span></button>
</div>
</div>
<hr/>
<div class="note-description">
{{ note.description }}
<br>
</div>
$scope.destroy = function(note, $index) {
Note.remove({id: note.id}, function() {
ShareNoteScope.getScope().notes.splice($index, 1);
});
$location.path('/notes');
}
Try this

Unknown Provider when adding service to controller

I created a Modal service and when I injected the service into the controller, I am receiving an error that says "$Injector: unpr Unknown Provider". Here is my code below. Let me know if I am missing something.
This is the service I have so far.
'use strict';
angular.module('myApp.services', [])
.factory('modalService', ['$scope', function($scope) {
return {
openMenuModal: function(templateLink, windowAnimation) {
var modalInstance = $modal.open({
templateUrl: templateLink,
backdrop: 'static',
windowClass: windowAnimation,
controller: function($scope, $modalInstance) {
$scope.close = function() {
$modalInstance.close();
};
},
size: 'md',
scope: $scope,
keyboard: true
});
}
};
}]);
Here is the controller I have set up.
angular.module('myApp.controllers', ['ui.bootstrap', 'ngAnimate'])
.controller('HomeCtrl', function($scope, $http, $modal, modalService) {
$scope.opentheBook = modalService.openMenuModal('partials/Books.html', 'animated zoomIn');
});
Here is the template for the data in the modal - Books.html
<div ng-controller="HomeCtrl">
<div class="modalBox animated fadeIn">
<button class="btn btn-danger pull-right" type="button" ng-click="" tooltip="Close"><i class="fa fa-times"></i></button>
<h1>title</h1>
<p>description</p>
<div class="next">
<button class="btn btn-danger pull-right" type="button" tooltip="Close"><i class="fa fa-times"></i></button>
</div>
</div>
</div>
Here is the main home page where I am calling the openBook() to open the modal with the info from the json
<div class="Books">
<ul>
<li ng-repeat="book in thing.Books" class="list-unstyled"><a ng-click="opentheBook" href="#"><h6>{{book.name}}</h6></a></li>
</ul>
</div>
json for Books example --inside another array called things
"Books": [
{
"name": "Name of Book 1",
"description": "Description about book..."
},
{
"name": "Name of Book 2",
"description": "Description about book..."
}
]
This error results from the $injector being unable to resolve a required dependency. To fix this, make sure the dependency is defined and spelled correctly. For example, the following code will fail with the same error you received -$injector:unpr, if myService is not defined:
angular.module('myApp', [])
.controller('MyController', ['myService', function (myService) {
// Do something with myService
}]);
Making sure each dependency is defined will fix the problem, as noted below.
angular.module('myApp', [])
.service('myService', function () { /* ... */ })
.controller('MyController', ['myService', function (myService) {
// Do something with myService
}]);
So to answer your question, in your case you appear to be missing dependency
angular.module('myApp.controllers', ['ui.bootstrap', 'ngAnimate'])
.controller('HomeCtrl', function($scope, $http, $modal, modalService) {
$scope.opentheBook = modalService.openMenuModal('partials/Books.html', 'animated zoomIn');
});
To Inject modalService like so:
.controller('HomeCtrl', ['modalService', function($scope, $http, $modal, modalService) {
}]);
You also need to change up your factory module to angular.module('myApp.services', ['ui.bootstrap']) and use $uibModal since $modal is deprecated.
angular.module('myApp', ['ui.bootstrap'])
.factory('modalService', ['$uibModal', function($uibModal) {
return {
openMenuModal: function(templateLink, windowAnimation) {
var modalObj = $uibModal.open({
templateUrl: templateLink,
backdrop: 'static',
windowClass: windowAnimation,
controller: function($scope,$modalInstance){
$scope.ok = function(id){
//Process OK Button Click
$modalInstance.close();
},
$scope.cancel = function(){
$modalInstance.dismiss('cancel');
}
},
size: 'md',
keyboard: true,
resolve: {
someData: function () {
return 'Return some Data';
}
}
});
}
};
}])
.controller('HomeCtrl', ['$scope','modalService', function($scope, modalService, someData) {
$scope.dataFromService = someData;
$scope.opentheBook = function(){
modalService.openMenuModal('myModalContent.html', 'animated zoomIn');
};
}]);
UPDATE 1
As mentioned in the comments, do not attempt to inject $scope to your factory. Here is a Plunker I created which lets you open a modal by calling the factory.
http://plnkr.co/edit/G68NVYZlTqrIS0N2TKL4

Categories