AngularJS: $rootScope.$watch not working as expected - javascript

I'm trying to use the $rootScope to track favorites in my application, as they are modified I want to tell the application to update local storage to match.
In my controller I am using the following function to add / delete favorites:
$scope.toggleFavorite = function(product) {
var item = {
id: product.id,
name: product.name
}
if (_.findWhere($rootScope.favoriteDrinks, item)) {
console.log('Rootscope contains the item: Removing');
$rootScope.favoriteDrinks = _.reject($rootScope.favoriteDrinks, function(favorite) {
return favorite.id === item.id;
});
} else {
console.log('Rootscope doesn\'t contain the item: Adding');
$rootScope.favoriteDrinks.push(item);
}
console.log($rootScope.favoriteDrinks);
}
The console.log() produces expected results, it is updating and removing favorites as I add them throughout the application.
For the $rootScope I have the following code in my app.js`:
.run(['localStorageService', '$rootScope', function(localStorageService, $rootScope) {
if (!localStorageService.get('favoriteDrinks')) { localStorageService.add('favoriteDrinks', []) };
_.extend($rootScope, {
favoriteDrinks: localStorageService.get('favoriteDrinks')
});
$rootScope.$watch('favoriteDrinks', function() {
console.log('Favorite Drinks Modified');
});
}]);
So on application startup, if the localstorage keys don't exist, I create empty ones, then extend the $rootScope to contain the favorites as retrieved from localStorage. Then I add the $watch to the $rootScope, however it is only firing the console.log() when I remove something from the $rootScope, what am I doing wrong?

Hmm, I am not sure what _.reject(...) do, but I think it is asynchronous.
To make the $watch statement works properly, we need to put the update statement to an asynchronous call. In your case, you should you $apply or $timeout.
Just try:
$rootScope.$apply(function () {
$rootScope.favoriteDrinks.push(item);
});
or
$timeout(function () {
$rootScope.favoriteDrinks.push(item);
});
Using $timeout maybe hack-ish, but it can avoid $diggest already in process problem.
More info about $apply and $timeout.

Related

Angular ionic badge count not updating

I am new to angular and believe i am not fully understanding the digest cycle.
I am trying to update a badge count in a ion-tab.(using ionic)
"ion-tab"
<ion-tab title="Requests" badge="data.badge" ng-controller="RequestTabCtrl" badge-style="badge-assertive" icon-off="ion-pull-request" icon-on="ion-pull-request" href="#/tab/requests">
<ion-nav-view name="tab-requests"></ion-nav-view>
I have written a factory that will store and array. this array is updated through socket.io
"notifications factory"
.factory('notifications',function(){
var list = [];
return{
all: function(){
return list;
},
add: function(data){
list.push(data);
},
length: function(){
return list.length;
}
};
});
.controller('RequestTabCtrl',function($scope,notifications){
$scope.data = {
badge : notifications.length()
};
});
My problem is that the badge count is not updating when the notifications array is updated through socket.io. I have checked that the array is being updated. In fact i can console log the array length and can see it it changing. Also i have set a scope variable in the ion-tab's child io-nav-view and as a result can see the expression {{requests.length}} be updated in this view.
.controller('RequestsCtrl', function($scope,notifications) {
$scope.requests = notifications.all();
})
I have tried $watch(in RequestTabCtrl) on notifications.length. i have tried calling $apply(in RequestTabCtrl) which results in a $digest already in progress. I have tried $timeout and see no positive result (in RequestTabCtrl and the factory length function). Help will me much appreciated.
thanks to AjinderSingh, the solution was found.
So two ways to go about this. First using the $interval approach:
.controller('RequestTabCtrl',function($scope,notifications,$interval){
$interval(function(){
$scope.data = {
badge : notifications.length()
};
},2000);
});
Second approach is to $broadcast from the factory after an item has been added to the array. followed by catching this event in the controller:
.factory('notifications',function($rootScope){
var list = [];
return{
all: function(){
return list;
},
add: function(data){
list.push(data);
$rootScope.$broadcast('update');
},
length: function(){
return list.length;
}
};
});
.controller('RequestTabCtrl',function($scope,notifications,$interval){
$scope.$on('update',function(){
$scope.data = {
badge : notifications.length()
};
});
});
I am choosing the second approach as it seems to be cleaner.
$ionicPlatform.ready(function() {
$cordovaBadge.promptForPermission();
$scope.setBadge = function(value) {
$cordovaBadge.hasPermission().then(function(result) {
$cordovaBadge.set(value);
}, function(error) {
alert(error);
});
}
});
For complete reference plz check https://www.thepolyglotdeveloper.com/2015/07/modify-the-badge-number-of-an-ionic-framework-app/

Invalidating all $http caches in Angular

I have an Angular application with a number of services based on Angular's built-in $resource service. Many of these use the cacheFactory to create their own independent caches. However, I want to blow all of these away (both the named caches and the "default" $http cache) when someone logs out. Right now I'm accomplishing this with location.reload(true), which certainly works, but it would be nice to achieve it without the reload if it's possible without totally changing the structure of the application.
To clarify, I'm aware that I can remove the cached values if I have a reference to the individual cache in scope, but what I want to do is to remove all caches, across the board, without necessarily having to know what they're all called.
You can inject $cacheFactory and get the cache object from the factory constructor (eg: $cacheFactory.get('$http')) and use removeAll() to cleanup all the cache. Use destroy() if you want to remove the cache object altogether.
In order to get all the cacheObject id's you could use $cacheFactory.info() which will return object with summary info for each cache object {id:'cacheObjId', size:'cacheSize'}.
Example:-
angular.forEach($cacheFactory.info(), function(ob, key) {
$cacheFactory.get(key).removeAll();
});
You could add removeAll/ destroyAll function to the cacheFactory so that you can use it anywhere else by decorating the $cacheFactory, something like this.
.config(['$provide',
function($provide) {
$provide.decorator('$cacheFactory', function($delegate) {
$delegate.removeAll = function() {
angular.forEach($delegate.info(), function(ob, key) {
$delegate.get(key).removeAll();
});
}
$delegate.destroyAll = function() {
angular.forEach($delegate.info(), function(ob, key) {
$delegate.get(key).destroy();
});
}
return $delegate;
});
}
])
angular.module('App', [])
.config(['$provide',
function($provide) {
$provide.decorator('$cacheFactory', function($delegate) {
$delegate.removeAll = function() {
angular.forEach($delegate.info(), function(ob, key) {
$delegate.get(key).removeAll();
});
}
$delegate.destroyAll = function() {
angular.forEach($delegate.info(), function(ob, key) {
$delegate.get(key).destroy();
});
}
return $delegate;
});
}
])
.run(function($cacheFactory) {
var value = 123;
$cacheFactory('cache1').put('test', value);
$cacheFactory('cache2').put('test', value);
console.log($cacheFactory.info());
$cacheFactory.removeAll();
console.log($cacheFactory.info());
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App">
</div>

Angular: Updating different controller through service or better method

I have a UserService
angular.module('mango.services', [])
.factory('UserService', function() {
var user = {
id: null,
name: 'anonymous.'
};
function getUser(){
return user;
}
function setUser(val){
user = val;
}
return {
getUser: getUser,
setUser: setUser,
}
});
a NavbarController
.controller('NavbarController', ['$scope','$location','UserService', function($scope, $location, UserService){
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
$scope.username = UserService.getUser().name;
}])
and a UserController where I have registerUser and loginUser functions.
.controller('UserController', ['$scope', '$http', 'UserService', function($scope, $http, UserService) {
$scope.loginUser = function(){
$http.post('/api/1.0/user/authenticate', $scope.user)
.success(function(data,status,headers,config){
if (data["valid"] === true) {
UserService.setUser(data.user);
} else {
$scope.flashes = data.flashes;
$scope.user.password = "";
}
})
}
and the HTML
<li ng-switch="username">
<a ng-class="{ active: isActive('/user/login')}" href="#/user/login" ng-switch-when="anonymous."><i class="fa fa-sign-in"></i> Sign in</a>
<a ng-class="{ active: isActive('/user/logout')}" href="#/user/logout" ng-switch-default><i class="fa fa-sign-out"></i> Sign out</a>
</li>
As you can see I'm trying to set the user of UserService if data.valid is true.
The server is returning a valid json object.
But the username value in NavbarController remains "anonymous." .
I'm not very experienced in JS, but I read something about broadcast and watch. I believe this might be the right approach. But maybe there's a better one.
I believe why it's not working is because the factory returns a singleton. But then using a factory is pointless.
So essentially what I want is, if credentials valid set user.name user.id client-app-wide. Later it should go through an "check if client user is valid" service. My session cookie is encrypted. But that's out of scope of the question.
All I need right now is to set the app's or rather the NavbarController's user data from UserController. How do I do that so it also updates the DOM aka ng-switch getting a different value.
It is not working because you are not creating a binding of some kind: with $scope.username = UserService.getUser().name you get the user name at that instant of time (which is anonymous) and hold on to it forever. One way out of this is with a watch. In NavbarController, replace the previous code with:
$scope.$watch(
function() {
return UserService.getUser().name;
},
function(newval) {
$scope.username = newval;
}
);
This will incur your application with a function call in every digest cycle. This function call is not slow, so it wouldn't matter.
If you do not want this overhead, you can also do it with events. In NavbarController:
$scope.username = UserService.getUser().name;
$scope.on("loggedIn", function(event, newUserName) {
$scope.username = newUserName;
});
And in UserController (add $rootScope to the dependencies):
if (data["valid"] === true) {
UserService.setUser(data.user);
$rootScope.$broadcast("loggedIn", data.user);
}
You indeed do need a $watcher to sync username in the NavbarController and UserService instead of $scope.username = UserService.getUser().name; which only sets up the initial value of $scope.username when the Controller is initialised:
$scope.$watch(
function () { return UserService.getUser().name; },
function (newVal) {
$scope.username = newVal;
}
);
The factory indeed designed to be a singleton across the application and that is the place where you should save the state of the application (i.e. your models, like the User model). The controllers are ephemeral and are created anew each time a template is created.
However, if you have a long lived Controller (like your NavbarControll), then the onus of maintaining a sync between the services and the controller is on the programmer using $watch.
Broadcasting messages is useful in some cases when inter-controller communication (which does not necessarily involve the models) is needed.
You can same approach without using $watch.
I have written a short function that let you put data in Object without replace it.
You can use it in you service. This way youu don't need to use watch. You can use the normal digest loop of Angular.
For example, see this simple controller & service:
Demo: JSFidde - http://jsfiddle.net/y09kx7f7/1/ with assert tests
Controller:
app.controller('dem',function($scope,me){
$scope.user=me.user; // {name:'user name'}
})
The controller will be chnage automatically without watch every time the user name changed!
Service
.factory('me',function($timeout){
var obj={}
obj.user={name:'hello'}
$timeout(function(){ //Example of change the data
newUser={name:'israel'}
cloneInto(obj.user,newUser)
},1000)
return obj
})
The cloneInto function that I written:
// The function it is like a=b,
// but keeping the object in his original memory position.
function cloneInto(a,b){
var i
for (i in a){
if(typeof a[i]!='object') //For supporting deep-copy
delete a[i]
}
for (i in b){
if (typeof b[i]=='object'){
if(!a[i]) a[i]={}
cloneInto(a[i],b[i])
}
else{
a[i]=b[i]
}
}
}

Is this a good way to keep data in sync between two controllers?

I have got a page layout with two controllers at the same time, one holds the data displayed as kind of side navigation, based on data stored the browsers local storage and at least one other controller, which is bind to a route and view.
I created this little wire frame graphic below which show the page layout:
The second controller is used for manipulating the local stored data and performs actions like adding a new item or deleting an existing one. My goal is to keep the data in sync, if an item got added or deleted by the 'ManageListCrtl' the side navigation using the 'ListCtrl' should get updated immediately.
I archived this by separating the local storage logic into a service which performs a broadcast when the list got manipulated, each controller listens on this event and updates the scope's list.
This works fine, but I'm not sure if there is the best practice.
Here is a stripped down version of my code containing just the necessary parts:
angular.module('StoredListExample', ['LocalObjectStorage'])
.service('StoredList', function ($rootScope, LocalObjectStorage) {
this.add = function (url, title) {
// local storage add logic
$rootScope.$broadcast('StoredList', list);
};
this.delete = function (id) {
// local storage delete logic
$rootScope.$broadcast('StoredList', list);
};
this.get = function () {
// local storage get logic
};
});
angular.module('StoredListExample')
.controller('ListCtrl', function ($scope, StoredList) {
$scope.list = StoredList.get();
$scope.$on('StoredList', function (event, data) {
$scope.list = data;
});
});
angular.module('StoredListExample')
.controller('ManageListCtrl', function ($scope, $location, StoredList) {
$scope.list = StoredList.get();
$scope.add = function () {
StoredList.add($scope.url, $scope.title);
$location.path('/manage');
};
$scope.delete = function (id) {
StoredList.delete(id);
};
$scope.$on('StoredList', function (event, data) {
$scope.list = data;
});
});
I don't see anything wrong with doing it this way. Your other option of course is to just inject $rootScope into both controllers and pub/sub between them with a $rootScope.$broadcast and a $rootScope.$on.
angular.module('StoredListExample')
.controller('ListCtrl', function ($scope, $rootScope) {
$scope.list = [];
$rootScope.$on('StoredList', function (event, data) {
$scope.list = data;
});
});
angular.module('StoredListExample')
.controller('ManageListCtrl', function ($scope, $rootScope, $location) {
$scope.list = [];
$scope.add = function () {
//psuedo, not sure if this is what you'd be doing...
$scope.list.push({ url: $scope.url, title: $scope.title});
$scope.storedListUpdated();
$location.path('/manage');
};
$scope.delete = function (id) {
var index = $scope.list.indexOf(id);
$scope.list.splice(index, 1);
$scope.storedListUpdated();
};
$scope.storedListUpdated = function () {
$rootScope.$broadcast('StoredList', $scope.list);
};
});
Additionally, you can achieve this in a messy but fun way by having a common parent controller. Whereby you would $emit up a 'StoredListUpdated' event from 'ManageListCtrl' to the parent controller, then the parent controller would $broadcast the same event down to the 'ListCtrl'. This would allow you to avoid using $rootScope, but it would get pretty messy in terms of readability as you add more events in this way.
It is always a better practice to use a common service that is a singleton for sharing the data between the 2 controllers - just make sure you use only references and not creating a local object in one of the controllers that should actually be in the service

Maintain model of scope when changing between views in AngularJS

I am learning AngularJS. Let's say I have /view1 using My1Ctrl, and /view2 using My2Ctrl; that can be navigated to using tabs where each view has its own simple, but different form.
How would I make sure that the values entered in the form of view1 are not reset, when a user leaves and then returns to view1 ?
What I mean is, how can the second visit to view1 keep the exact same state of the model as I left it ?
I took a bit of time to work out what is the best way of doing this. I also wanted to keep the state, when the user leaves the page and then presses the back button, to get back to the old page; and not just put all my data into the rootscope.
The final result is to have a service for each controller. In the controller, you just have functions and variables that you dont care about, if they are cleared.
The service for the controller is injected by dependency injection. As services are singletons, their data is not destroyed like the data in the controller.
In the service, I have a model. the model ONLY has data - no functions -. That way it can be converted back and forth from JSON to persist it. I used the html5 localstorage for persistence.
Lastly i used window.onbeforeunload and $rootScope.$broadcast('saveState'); to let all the services know that they should save their state, and $rootScope.$broadcast('restoreState') to let them know to restore their state ( used for when the user leaves the page and presses the back button to return to the page respectively).
Example service called userService for my userController :
app.factory('userService', ['$rootScope', function ($rootScope) {
var service = {
model: {
name: '',
email: ''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
}]);
userController example
function userCtrl($scope, userService) {
$scope.user = userService;
}
The view then uses binding like this
<h1>{{user.model.name}}</h1>
And in the app module, within the run function i handle the broadcasting of the saveState and restoreState
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
As i mentioned this took a while to come to this point. It is a very clean way of doing it, but it is a fair bit of engineering to do something that i would suspect is a very common issue when developing in Angular.
I would love to see easier, but as clean ways to handle keeping state across controllers, including when the user leaves and returns to the page.
A bit late for an answer but just updated fiddle with some best practice
jsfiddle
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
var userService = {};
userService.name = "HI Atul";
userService.ChangeName = function (value) {
userService.name = value;
};
return userService;
});
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
$scope.updatedname="";
$scope.changeName=function(data){
$scope.updateServiceName(data);
}
$scope.updateServiceName = function(name){
UserService.ChangeName(name);
$scope.name = UserService.name;
}
}
$rootScope is a big global variable, which is fine for one-off things, or small apps.
Use a service if you want to encapsulate your model and/or behavior (and possibly reuse it elsewhere). In addition to the google group post the OP mentioned, see also https://groups.google.com/d/topic/angular/eegk_lB6kVs/discussion.
Angular doesn't really provide what you are looking for out of the box. What i would do to accomplish what you're after is use the following add ons
UI Router & UI Router Extras
These two will provide you with state based routing and sticky states, you can tab between states and all information will be saved as the scope "stays alive" so to speak.
Check the documentation on both as it's pretty straight forward, ui router extras also has a good demonstration of how sticky states works.
I had the same problem, This is what I did:
I have a SPA with multiple views in the same page (without ajax), so this is the code of the module:
var app = angular.module('otisApp', ['chieffancypants.loadingBar', 'ngRoute']);
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/:page', {
templateUrl: function(page){return page.page + '.html';},
controller:'otisCtrl'
})
.otherwise({redirectTo:'/otis'});
}]);
I have only one controller for all views, but, the problem is the same as the question, the controller always refresh data, in order to avoid this behavior I did what people suggest above and I created a service for that purpose, then pass it to the controller as follows:
app.factory('otisService', function($http){
var service = {
answers:[],
...
}
return service;
});
app.controller('otisCtrl', ['$scope', '$window', 'otisService', '$routeParams',
function($scope, $window, otisService, $routeParams){
$scope.message = "Hello from page: " + $routeParams.page;
$scope.update = function(answer){
otisService.answers.push(answers);
};
...
}]);
Now I can call the update function from any of my views, pass values and update my model, I haven't no needed to use html5 apis for persistence data (this is in my case, maybe in other cases would be necessary to use html5 apis like localstorage and other stuff).
An alternative to services is to use the value store.
In the base of my app I added this
var agentApp = angular.module('rbAgent', ['ui.router', 'rbApp.tryGoal', 'rbApp.tryGoal.service', 'ui.bootstrap']);
agentApp.value('agentMemory',
{
contextId: '',
sessionId: ''
}
);
...
And then in my controller I just reference the value store. I don't think it holds thing if the user closes the browser.
angular.module('rbAgent')
.controller('AgentGoalListController', ['agentMemory', '$scope', '$rootScope', 'config', '$state', function(agentMemory, $scope, $rootScope, config, $state){
$scope.config = config;
$scope.contextId = agentMemory.contextId;
...
Solution that will work for multiple scopes and multiple variables within those scopes
This service was based off of Anton's answer, but is more extensible and will work across multiple scopes and allows the selection of multiple scope variables in the same scope. It uses the route path to index each scope, and then the scope variable names to index one level deeper.
Create service with this code:
angular.module('restoreScope', []).factory('restoreScope', ['$rootScope', '$route', function ($rootScope, $route) {
var getOrRegisterScopeVariable = function (scope, name, defaultValue, storedScope) {
if (storedScope[name] == null) {
storedScope[name] = defaultValue;
}
scope[name] = storedScope[name];
}
var service = {
GetOrRegisterScopeVariables: function (names, defaultValues) {
var scope = $route.current.locals.$scope;
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
if (storedBaseScope == null) {
storedBaseScope = {};
}
// stored scope is indexed by route name
var storedScope = storedBaseScope[$route.current.$$route.originalPath];
if (storedScope == null) {
storedScope = {};
}
if (typeof names === "string") {
getOrRegisterScopeVariable(scope, names, defaultValues, storedScope);
} else if (Array.isArray(names)) {
angular.forEach(names, function (name, i) {
getOrRegisterScopeVariable(scope, name, defaultValues[i], storedScope);
});
} else {
console.error("First argument to GetOrRegisterScopeVariables is not a string or array");
}
// save stored scope back off
storedBaseScope[$route.current.$$route.originalPath] = storedScope;
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
},
SaveState: function () {
// get current scope
var scope = $route.current.locals.$scope;
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
// save off scope based on registered indexes
angular.forEach(storedBaseScope[$route.current.$$route.originalPath], function (item, i) {
storedBaseScope[$route.current.$$route.originalPath][i] = scope[i];
});
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
}
}
$rootScope.$on("savestate", service.SaveState);
return service;
}]);
Add this code to your run function in your app module:
$rootScope.$on('$locationChangeStart', function (event, next, current) {
$rootScope.$broadcast('savestate');
});
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
Inject the restoreScope service into your controller (example below):
function My1Ctrl($scope, restoreScope) {
restoreScope.GetOrRegisterScopeVariables([
// scope variable name(s)
'user',
'anotherUser'
],[
// default value(s)
{ name: 'user name', email: 'user#website.com' },
{ name: 'another user name', email: 'anotherUser#website.com' }
]);
}
The above example will initialize $scope.user to the stored value, otherwise will default to the provided value and save that off. If the page is closed, refreshed, or the route is changed, the current values of all registered scope variables will be saved off, and will be restored the next time the route/page is visited.
You can use $locationChangeStart event to store the previous value in $rootScope or in a service. When you come back, just initialize all previously stored values. Here is a quick demo using $rootScope.
var app = angular.module("myApp", ["ngRoute"]);
app.controller("tab1Ctrl", function($scope, $rootScope) {
if ($rootScope.savedScopes) {
for (key in $rootScope.savedScopes) {
$scope[key] = $rootScope.savedScopes[key];
}
}
$scope.$on('$locationChangeStart', function(event, next, current) {
$rootScope.savedScopes = {
name: $scope.name,
age: $scope.age
};
});
});
app.controller("tab2Ctrl", function($scope) {
$scope.language = "English";
});
app.config(function($routeProvider) {
$routeProvider
.when("/", {
template: "<h2>Tab1 content</h2>Name: <input ng-model='name'/><br/><br/>Age: <input type='number' ng-model='age' /><h4 style='color: red'>Fill the details and click on Tab2</h4>",
controller: "tab1Ctrl"
})
.when("/tab2", {
template: "<h2>Tab2 content</h2> My language: {{language}}<h4 style='color: red'>Now go back to Tab1</h4>",
controller: "tab2Ctrl"
});
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<body ng-app="myApp">
Tab1
Tab2
<div ng-view></div>
</body>
</html>

Categories