Watch for changes to session storage without $interval - angularjs

I am building an app in which I save data in one controller to session storage, and in my other controllers I use $interval to constantly watch the sessionStorage to check for changes like so.
$interval(function(){
vm.myData = JSON.parse(sessionStorage.getItem('patient'));
}, 300)
I feel like this is not a good way to keep watching, because, for example, if I want to allow a user to edit some of the data in vm.myData, they cant, as the variable keeps updating itself.
Is there a way to simply watch the sessionStorage object to see if 'patient' has changed? I tried to use the $watch function, but i don't think I quite understand how it works.

One approach is to use the controller $doCheck Life-Cycle Hook:
this.$doCheck = function () {
var previousValue;
var currentValue;
previousValue = currentValue;
currentValue = sessionStorage.getItem('patient'));
if (currentValue !== previousValue) {
console.log("patient changed");
};
};
For more information, see AngularJS $compile Service API Reference -- Life-Cycle Hooks.

Related

Firebase snapshot.val() not binding to $scope

I'm using FireBase and trying to do some queries, the results are logging in but are not visible in the HTML $scope.
var shopRef = firebaseDataService.intro;
$scope.shops = [];
var taskRef = shopRef.orderByChild("cat").equalTo("Accomodation");
taskRef.on("value", function(snapshot) {
var snapData = snapshot.val();
console.log(snapData);
$scope.shops.push(snapData);
});
When I use $scope.$apply(), I manage to get the data updated to shops, but it's still not passing anything to my directive .
<search-card shops="shops"> </search-card>
<p> Shops are {{shops}}</p>
I got it working somehow with $firebaseArray
$scope.shops = $firebaseArray(taskRef);
but I`d still like to know what I'm doing wrong and why it's not working with the snapshot.
From the angularfire docs:
// read data from the database into a local scope variable
ref.on("value", function(snapshot) {
// Since this event will occur outside Angular's $apply scope, we need to notify Angular
// each time there is an update. This can be done using $scope.$apply or $timeout. We
// prefer to use $timeout as it a) does not throw errors and b) ensures all levels of the
// scope hierarchy are refreshed (necessary for some directives to see the changes)
$timeout(function() {
$scope.data = snapshot.val();
});
});
It seems that using $scope.apply() will not refresh the entire hierarchy (and hence the directive). Try using $timeout as prescribed instead
That being said, I think you should go with the $firebaseArray() option as that strikes me as the most "angular" solution

AngularJS 1.5.x $onChanges Not Working with One-Way Binding Changes

I don't understand why $onChanges isn't kicked off when I change a bound primitive in an input. Can someone see what I've done wrong, and explain this in an uncomplicated way? I made a plunkr of a quick test application after I couldn't get it to work in my actual application either.
angular
.module('test', [])
.component('test', {
template: '<child application="vm.application"></child>',
controller: 'testCtrl as vm'
})
.controller('testCtrl', function() {
var vm = this;
vm.$onInit = function () {
vm.application = {
data: {
name: 'Test'
}
}
};
})
.component('child', {
template: '<input type="text" ng-model="vm.application.data.name">',
bindings: {
application: '<'
},
controller: 'childCtrl as vm'
})
.controller('childCtrl', function() {
var vm = this;
vm.$onChanges = function (changes) {
console.log('CHANGED: ', changes);
};
})
The $onChanges method is not called for changes on subproperties of an object. Default changes to objects generally follow this sequence within a components lifetime:
UNINITIALIZED_VALUE to undefined
undefined to {} or { someAttribute: someValue, .. }
({..} to undefined if you delete the object in a parent scope)
In order to watch subproperties you could use the $doCheck method that was added in 1.5.8. It is called on every digest cycle and it takes no parameters. With great power comes great responsibility. In that method you would put logic that detects whether a certain value has been updated or not - the new value will already be updated in the controller's scope, you just need to find a way to determine if the value changed compared to the previously known value.
You could set a previousValueOfObjectAttribute variable on the controller before you start to expect changes to this specific attribute (e.g. when subcomponent B calls an output binding function in component A, based on which the target object - which is an input binding to B - in A changes). In cases where it is not predictable when the change is about to occur, you could make a copy of the specific atributes of interest after any change observed via the $doCheck method.
In my specific use case, I did not explicitly check between an old and new value, but I used a promise (store $q.defer().promise) with the intention that any change I would 'successfully' observe in the $doCheck method would resolve that promise. My controller then looked something like the following:
dn.$doCheck = function () {
if (dn.waitForInputParam &&
dn.waitForInputParam.promise.$$state.status === 0 &&
dn.targetObject.targetAttribute !== false)
dn.waitForInputParam.resolve(dn.targetObject.targetAttribute);
}
dn.listenToInputChange = function () {
dn.waitForInputParam = $q.defer();
dn.waitForInputParam.promise.then(dn.onInputParamChanged);
}
dn.onInputParamChanged = function (value) {
// do stuff
//
// start listening again for input changes -- should be async to prevent infinite $digest loop
setTimeout(dn.listenToInputChange, 1);
}
(w.r.t. promise.$$state.status, see this post).
For all other intents and purposes, watching changes to primitive data types, you should still use $onChanges. Reference: https://docs.angularjs.org/guide/component
It's $onChanges and not $onChange.
Also, the onChange only updates when the parent value is changed, not the child. Take a look at this plunkr. Note the console.log only fires when you type in the first input.
As others said above, Angular does not watch for changes in object properties, however, you can make Angular believe that your object is changed by reference.
It is sufficient to do a shallow copy of the object in order to trigger an $onChanges event:
vm.campaign = angular.extend({}, vm.campaign);
Credits to #gkalpak
Dealing with $onChanges is tricky. Actually, thats why in version 1.5.8 they introduced the $doCheck, similar to Angular 2 ngDoCheck.
This way, you can manually listen to changes inside the object being listened, which does not occur with the $onChanges hook (called only when the reference of the object is changed). Its the same thing, but it gets called for every digest cycle allowing you to check for changes manually (but better then watches).
For more details, see this blog post.

angularfireCollection: know when the data is fully loaded

I am writing a small Angular web application and have run into problems when it comes to loading the data. I am using Firebase as datasource and found the AngularFire project which sounded nice. However, I am having trouble controlling the way the data is being displayed.
At first I tried using the regular implicit synchronization by doing:
angularFire(ref, $scope, 'items');
It worked fine and all the data was displayed when I used the model $items in my view. However, when the data is arriving from the Firebase data source it is not formatted in a way that the view supports, so I need to do some additional structural changes to the data before it is displayed. Problem is, I won't know when the data has been fully loaded. I tried assigning a $watch to the $items, but it was called too early.
So, I moved on and tried to use the angularfireCollection instead:
$scope.items = angularFireCollection(new Firebase(url), optionalCallbackOnInitialLoad);
The documentation isn't quite clear what the "optionalCallbackOnInitialLoad" does and when it is called, but trying to access the first item in the $items collection will throw an error ("Uncaught TypeError: Cannot read property '0' of undefined").
I tried adding a button and in the button's click handler I logged the content of the first item in the $items, and it worked:
console.log($scope.items[0]);
There it was! The first object from my Firebase was displayed without any errors ... only problem is that I had to click a button to get there.
So, does anyone know how I can know when all the data has been loaded and then assign it to a $scope variable to be displayed in my view? Or is there another way?
My controller:
app.controller('MyController', ['$scope', 'angularFireCollection',
function MyController($scope, angularFireCollection) {
$scope.start = function()
{
var ref = new Firebase('https://url.firebaseio.com/days');
console.log("start");
console.log("before load?");
$scope.items = angularFireCollection(ref, function()
{
console.log("loaded?");
console.log($scope.items[0]); //undefined
});
console.log("start() out");
};
$scope.start();
//wait for changes
$scope.$watch('items', function() {
console.log("items watch");
console.log($scope.items[0]); //undefined
});
$scope.testData = function()
{
console.log($scope.items[0].properties); //not undefined
};
}
]);
My view:
<button ng-click="testData()">Is the data loaded yet?</button>
Thanks in advance!
So, does anyone know how I can know when all the data has been loaded
and then assign it to a $scope variable to be displayed in my view? Or
is there another way?
Remember that all Firebase calls are asynchronous. Many of your problems are occurring because you're trying to access elements that don't exist yet. The reason the button click worked for you is because you clicked the button (and accessed the elements) after they had been successfully loaded.
In the case of the optionalCallbackOnInitialLoad, this is a function that will be executed once the initial load of the angularFireCollection is finished. As the name implies, it's optional, meaning that you don't have to provide a callback function if you don't want to.
You can either use this and specify a function to be executed after it's loaded, or you can use $q promises or another promise library of your liking. I'm partial to kriskowal's Q myself. I'd suggest reading up a bit on asynchronous JavaScript so you get a deeper understanding of some of these issues.
Be wary that this:
$scope.items = angularFireCollection(ref, function()
{
console.log("loaded?");
console.log($scope.items[0]); //undefined
});
does correctly specify a callback function, but $scope.items doesn't get assigned until after you've ran the callback. So, it still won't exist.
If you just want to see when $scope.items has been loaded, you could try something like this:
$scope.$watch('items', function (items) {
console.log(items)
});
In my project I needed to know too when the data has been loaded. I used the following approach (implicit bindings):
$scope.auctionsDiscoveryPromise = angularFire(firebaseReference.getInstance() + "/auctionlist", $scope, 'auctionlist', []);
$scope.auctionsDiscoveryPromise.then(function() {
console.log("AuctionsDiscoverController auctionsDiscoveryPromise resolved");
$timeout(function() {
$scope.$broadcast("AUCTION_INIT");
}, 500);
}, function() {
console.error("AuctionsDiscoverController auctionsDiscoveryPromise rejected");
});
When the $scope.auctionsDiscoveryPromise promise has been resolved I'm broadcasting an event AUCTION_INIT which is being listened in my directives. I use a short timeout just in case some services or directives haven't been initialized yet.
I'm using this if it would help anyone:
function getAll(items) {
var deferred = $q.defer();
var dataRef = new Firebase(baseUrl + items);
var returnData = angularFireCollection(dataRef, function(data){
deferred.resolve(data.val());
});
return deferred.promise;
}

How to disassociate angularFire bound object?

I am using AngularJS and FireBase in my application. I bound an object to be in sync with FireBase:
$scope.winnerPromise = angularFire(travelBidsFirebaseRef + "/user/" + $scope.auction.winnerUserId, $scope, 'winner', {});
Now I want to disassociate $scope.winner, meaning I want it to stay safe in the FireBase DB, but I don't want my scope variable 'winner' to be synchronized with it anymore. How do I do that? I saw disassociate() finction in angularfire.js but I don't see how I can use it. Any ideas?
The disassociate function is passed to you when the promise is resolved. I'd use it as follows:
var ref = travelBidsFirebaseRef.child("user/" + $scope.auction.winnerUserId);
var promise = angularFire(ref, $scope, "winner", {});
promise.then(function(disassociate) {
// Do some work...
disassociate(); // Don't synchronize $scope.winner anymore.
});
Hope this helps!
I am using angularfire and for me it worked the $destroy method.
https://github.com/firebase/angularfire/blob/master/docs/reference.md#destroy-1

I cannot add items in an array using the setTimeout function

I'm trying to update the ui by pushing a new entry into an array but for some reason the ui is not updated until the next operation on the array.
function TestCtrl($scope){
$scope.projects = [{name: "project1"}];
$scope.test = function(){ return "batman"; };
$scope.addNew = function(){
$scope.projects.push({name: "project2"});
setTimeout(function(){
$scope.projects.push({name: "project3"});
}, 1000);
};
}
And here is an example http://jsbin.com/itasis/4/edit
I didn't tested yet but I expect the same issue in behavior from an ajax request.
Use $timeout instead of setTimeout. $timeout automatically calls $apply() for us, triggering an Angular digest cycle, which will update any views that need to be refreshed.
Regarding AJAX, I would encourage you to use Angular's $http service, which will also call $apply() for us. Otherwise, in your AJAX callback, after updating your Angular models/scope, manually call scope.$apply().

Resources