AngualrJS $watchCollection triggers even when arrays are equal - angularjs

I am trying to implement an auto sync between my angularJS model and my database.
I am running the following function every ten seconds to get data from from database in which I update my variable products_copy:
$interval(function(){$scope.getProductsSync();},10000);
$scope.getProductsSync = function() {
var q = $q.defer();
$http({
url: '/getData/getProducts.php',
method: "POST",
data: {"user_id":$scope.user_id}
})
.then(function(response) {
if(response.data.valid)
{
console.log('Products sync complete: '+new Date().toLocaleTimeString());
console.log(response.data.products);
$scope.products_copy = response.data.products;
q.resolve('Products sync complete');
}
else if(response.data.msg=="offline")
{
console.log('Products sync offline');
q.resolve('Products sync offline');
}
else
{
console.log('Products sync error');
console.log(response);
q.reject('Products sync error');
}
},
function(response) {
console.log('Products sync error');
console.log(response);
q.reject('Products sync error');
});
return q.promise;
}
Whenever there is a change in this data I want to update my actual product list in my model which is defined by the array products. Hence, I am using the service $watchCollection to detect a change in the data and update my model when there is a change. However this change is triggered in each call even though the data from the database is unchanged.
$scope.$watchCollection('products_copy', function (newValue, oldValue, scope) {
if(newValue!==oldValue)
{
console.log('Watch on products was called');
console.log('Old value: '+oldValue);
console.log('New value: '+newValue);
$scope.products = newValue;
}
});
I want the event to be triggered only when there is change in the array such as:
add item
remove item
edit any property of any item
EDIT 1:
I changed it to angular.equals but even that resulted in trigger in every call. However, when I examined each item in the console I realised angular was adding a property $$hashkey which was varying between the items. Any idea how to solve this?

It is how it should be, because on each response you assign a new reference to $scope.products_copy and no matter that there're no changes of the data inside it, when you do newValue!==oldValue you compare the refereces, they are always different
if you try
var a = [];
var b = [];
console.log(a===b); // false
// the both are empty and seems to be equal
you have to check the data inside old and new data. Try with angular.equals

You can try for angular.equal(object1, object2)
$scope.$watchCollection('products_copy', function (newValue, oldValue, scope) {
if(!angular.equals(newValue, oldValue))
{
console.log('Watch on products was called');
console.log('Old value: '+oldValue);
console.log('New value: '+newValue);
$scope.products = newValue;
}
});

The problem was that angular was inserting a $$hashKey attribute which resulted in a difference even in same objects. Removing this field did the trick for me.

Related

Programmatically Select AngularJS Typeahead Option

I have a AngularJS Typeahead that retrieves matches asynchronously. When a barcode is scanned into the field, it returns the matching result, but the user still has to select it. I would like to automatically select the result if it's an exact match. I see that the typeahead has a select(idx) function, but am not sure how to get a reference to it from my controller.
I was envisioning something like this:
$scope.SearchItems = function (term) {
return $http.get('api/Items/Search', {
params: {
term: term
}
}).then(function (response) {
if (response.data.length == 1 && response.data[0].Code == term) {
// Somehow inform typeahead control to select response.data[0]
}
return response.data;
});
};
I had a similar issue and never figured how to access the typeahead's select(idx), but I managed to get this functionality working. Here's my hacky workaround....
$promise.then(function(res) {
angular.forEach(res, function(item, key) {
// if we have an exact match
if (item.title === term) {
// update model
$scope.src = item;
// find item in dropdown
var elm = '[id*=option-' + key + ']';
var opt = angular.element(document.querySelectorAll(elm));
//call click handler outside of digest loop
$timeout(function() {
opt.triggerHandler('click');
}, 0);
}
});
// return async results
return res;
});
Basically we just update our model manually, locate the element in our dropdown and then fire off the 'click' handler. Make sure you wrap the triggerHandler call in a $timeout() set to zero, otherwise you will get a $rootScope:inprog error since digest is already in progress.

Angular.js, $resource, how to manage multiple asynchronous requests

I am implementing a "copy on write" CRUD system meaning i never overwrite a database entry but mark as inactive and write a new record. When editing an existing record this means i write to the old record deactivating then create a new record. My controller code is below:
$scope.save = function() {
if(!$scope.newDevice){
var editDevice = $scope.device;
$scope.delete(editDevice);
$scope.device = {name: editDevice.name, type: editDevice.type, hash: editDevice.hash};
}
var newDevice = new DeviceService($scope.device);
newDevice = newDevice.$save(function(newDevice, putResponseHeaders) {
DeviceService.query({active : true}, function(devices){
$scope.devices = devices;
});
});
};
When i call to get the list of active devices with DeviceService.query({active : true} I still get the old record as active since it executes and returns before the delete method has been processed and returned.
I think i should be using promise maybe. How do i write this code to be better and work?
thanks
Yes, you want to use promises. You have two options:
Use the success/failure callbacks that all $resource methods supply. Note you're using this when you call $save. You could do the same when you call $delete on the resource, so that your remaining code only executes when the $delete() succeeds. These callbacks are automatically invoked when the $resource's built-in promise is resolved or rejected.
Make your $scope.delete() function return a promise. It sounds like this might be better, because you do not always want to make the delete request.
The code for #2 might look like this:
// this function use the '$q' service, which you need to inject
// in your controller
$scope.delete = function(item) {
var deferred = $q.defer();
item.$delete({},
function(response) {
// the delete succeeded, resolve the promise
deferred.resolve(response);
},
function(error) {
// failed, reject the promise
deferred.reject(error);
}
);
return deferred.promise;
}
$scope.save = function() {
if(!$scope.newDevice){
var editDevice = $scope.device;
$scope.delete(editDevice).then(function(response) {
$scope.device = {name: editDevice.name, type: editDevice.type, hash: editDevice.hash};
// now trigger the code to save the new device (or whatever)
$scope.doTheActualSave();
},
function(error) { });
} else {
// there was nothing to delete, just trigger the code to save
$scope.doTheActualSave();
}
};
$scope.doTheActualSave = function() {
var newDevice = new DeviceService($scope.device);
newDevice = newDevice.$save(function(newDevice, putResponseHeaders) {
DeviceService.query({active : true}, function(devices){
$scope.devices = devices;
});
});
}

WebSQL data into AngularJs DropDown

I have very simple question about getting data from WebSql
I have DropDown i.e
<select id="selectCatagoryFood" data-role="listview" data-native-menu="true"
ng-init="foodCatagory = foodCatagories.cast[0]"
ng-options="foodCatagory as foodCatagory.text for foodCatagory in foodCatagories.cast"
ng-model="foodCatagory"
ng-change="changeFoodCatagory()">
</select>
now i want to add data init from webSQL. I already get Data from webSql but i am confuse that how to add that data into DropDown
An example or hints maybe very helpful for me.
Update 1 :: Add Controller Code
myApp.controller('foodSelection',function($scope,foodCatagories){
$scope.foodCatagories = foodCatagories;
$scope.changeFoodCatagory = function(){
alert($scope.foodCatagory.value);
}
});
Update 2 webSQL and JayData
_context.onReady({
success: showData,
error: function (error){
console.log(error);
}
});
function showData(){
var option = '';
_context.FoodGroup.forEach(function(FG)
{
option += '<option value="'+FG.FoodGroupID+'">'+FG.Description+'</option>';
}).then(function(){
console.log(option);
});
}
Update 3
var myApp = angular.module('myApp',[]);
myApp.factory('foodCatagories',function(){
var foodCatagories = {};
foodCatagories.cast = [
{
value: "000",
text: "Select Any"
}
];
return foodCatagories;
});
Update 4
One thing that i didn't mention is that I am using JayData for getting data from webSQL to my App
I will try to explain how it works:
EDIT: Live demo
html
Here is your stripped down select.
<select ng-options="item as item.text for item in foodCategories"
ng-model="foodCategory"
ng-required="true"
ng-change="changeFoodCategory()">
</select>
The directive ng-options will fill automatically the option elements in your select. It will take the foodCategories variable from the $scope of your controller and foreach item in the collection, it will use the text property as the label shown (<option>{{item.text}}</option>') and it will select the whole objectitemas the value of the selectedoption. You could also refer to a property as the value like ({{item.text}}). Then yourng-modelwould be set to theid` value of the selected option.
The directive ng-model corresponds to the variable in the $scope of your controller that will hold the value of the selected option.
The directive ng-required allows you to check if a value has been selected. If you are using a form, you can check if the field is valid formName.ngModelName.$valid. See the docs for more details on form validation.
The directive ng-change allows you to execute a function whenever the selected option changes. You may want to pass the ng-model variable to this function as a parameter or call the variable through the $scope inside the controller.
If no default value is set, angular will add an empty option which will be removed when an option is selected.
You did use the ng-init directive to select the first option, but know that you could set the ng-model variable in your controller to the default value you would like or none.
js
Here I tried to simulate your database service by returning a promise in the case that you are doing an async request. I used the $q service to create a promise and $timeout to fake a call to the database.
myApp.factory('DbFoodCategories', function($q, $timeout) {
var foodCategories = [
{ id: 1, text: "Veggies", value: 100 },
{ id: 2, text: "Fruits", value: 50 },
{ id: 3, text: "Pasta", value: 200 },
{ id: 4, text: "Cereals", value: 250 },
{ id: 5, text: "Milk", value: 150 }
];
return {
get: function() {
var deferred = $q.defer();
// Your call to the database in place of the $timeout
$timeout(function() {
var chance = Math.random() > 0.25;
if (chance) {
// if the call is successfull, return data to controller
deferred.resolve(foodCategories);
}
else {
// if the call failed, return an error message
deferred.reject("Error");
}
}, 500);
/* // your code
_context.onReady({
success: function() {
deferred.resolve(_contect.FoodGroup);
},
error: function (error){
deferred.reject("Error");
}
});
*/
// return a promise that we will send a result soon back to the controller, but not now
return deferred.promise;
},
insert: function(item) {
/* ... */
},
update: function(item) {
/* ... */
},
remove: function(item) {
/* ... */
}
};
});
In your controller you set the variables that will be used in your view. So you can call your DbFoodCategories service to load the data into $scope.foodCategories, and set a default value in $scope.foodCategory that will be used to set the selected option.
myApp.controller('FoodSelection',function($scope, DbFoodCategories){
DbFoodCategories.get().then(
// the callback if the request was successfull
function (response) {
$scope.foodCategories = response; //response is the data we sent from the service
},
// the callback if an error occured
function (response) {
// response is the error message we set in the service
// do something like display the message
}
);
// $scope.foodCategory = defaultValue;
$scope.changeFoodCategory = function() {
alert($scope.foodCatagory.value);
}
});
I hope that this helped you understand more in detail what is happening!
See this example and how use $apply to update the data in scope.
in the new version we released a new module to support AngularJS. We've started to document how to use it, you can find the first blogpost here
With this you should be able to create your dropdown easily, no need to create the options manually. Something like this should do the trick:
myApp.controller('foodSelection',function($scope, $data) {
$scope.foodCatagories = [];
...
_context.onReady()
.then(function() {
$scope.foodCatagories = _context.FoodGroup.toLiveArray();
});
});
provided that FoodGroup has the right fields, of course

AngularJS: example of two-way data binding with Resource

I have a view Transaction which has two sections
a.) view-transaction
b.) add-transaction
both are tied to the following controller
function TransactionController($scope, Category, Transaction) {
$scope.categories = Category.query(function() {
console.log('all categories - ', $scope.categories.length);
});
$scope.transactions = Transaction.query();
$scope.save = function() {
var transaction = new Transaction();
transaction.name = $scope.transaction['name'];
transaction.debit = $scope.transaction['debit'];
transaction.date = $scope.transaction['date'];
transaction.amount = $scope.transaction['amount'];
transaction.category = $scope.transaction['category'].uuid;
//noinspection JSUnresolvedFunction
transaction.$save();
$scope.transactions.push(transaction);
console.log('transaction saved successfully', transaction);
}
}
, where Transaction is a service and looks as follows
angular.module('transactionServices', ['ngResource']).factory('Transaction', function($resource) {
return $resource('/users/:userId/transactions/:transactionId', {
// todo: default user for now, change it
userId: 'bd675d42-aa9b-11e2-9d27-b88d1205c810',
transactionId: '#uuid'
});
});
When i click on tab "Transaction", the route #/transactions is activated, causing it to render both sub-views a.) and b.)
The question that I have is,
- Is there a way to update the $scope.transactions whenever I add new transaction? Since it is a resource
or I will have to manually do $scope.transactions.push(transaction);
My very first answer so take it easy on me...
You can extend the Transaction resource to update the $scope.transactions for you. It would be something like:
angular.module( ..., function($resource) {
var custom_resource = $resource('/users/:userId/transactions/:transactionId', {
...
});
custom_resource.prototype.save_and_update = function (transactions) {
var self = this;
this.$save(function () {
transactions.push(self);
});
};
return custom_resource;
});
In you controller, you would then do:
function TransactionController (...) {
...
$scope.save = function () {
...
// In place of: transaction.$save(), do:
transaction.save_and_update($scope.transactions);
...
}
}
Note: You need to make sure that object you created is fully usable in $scope. I spent 30 min trying to figure why this method failed on my code and it turn out that I am generating identity code in the database. As result, all my subsequent action on added new object failed because the new object was missing the identity!!!
There is no way to update a set of models in the scope automatically. You can push it into the $scope.transactions, or you can call a method that updates $scope.transactions with fresh data from the server. In any case, you should update the $scope in the success callback of your resource save function like this:
transaction.$save({}, function() {
$scope.transactions.push(transaction);
//or
$scope.transactions = Transaction.query();
});
In your example, when you push the transaction, you cannot be sure that the model has been saved successfully yet.
Another tip: you can create the new Transaction before you save it, and update the model directly from your view:
$scope.newTransaction = new Transaction();
$scope.addTransaction = function() {
$scope.newTransaction.save( ...
}
And somewhere in your view:
<input type="text" ng-model="newTransaction.name" />
The ng-model directive ensures that the input is bound to the name property of your newTransaction model.

Backbone model.destroy(): Is explicit removal from collection necessary?

I have a simple question. I am looking at a function with 2 lines of code:
deleteTask: function() {
this.parent.collection.remove(this.model);
this.model.destroy();
}
If I comment out the first line, which is supposed to remove the model from its collection, things seem to work as intended (as in, the model is removed automatically). From Backbone's website, this is the relevant discription for a model's "destroy" function:
Triggers a "destroy" event on the model, which will bubble up through any collections that contain it.
Am I safe to assume that the removal of this.parent.collection.remove(this.model); will not affect the functionality of the code in any way? This is what I think, but I wanted to make sure of it.
Thank you!
If you destroy a model, it is removed from any collections that was containing it. You can see that in the backbone source
//Internal method called every time a model in the set fires an event.
_onModelEvent: function(event, model, collection, options) {
...
if (event === 'destroy') this.remove(model, options);
So yes, I wouldn't think you would need to remove the model from your collection explicitly.
But don't trust me, test for yourself :)
deleteTask: function() {
that = this;
this.model.destroy({
success: function() {
console.log(that.parent.collection);
}
});
}
Check the console for yourself to see whether the model was removed from the collection.
The solution is to override the Backbone model destroy function. I made this on an abstract model with success and callback strategy:
Parameter "data" corresponds to the original parameter "resp".
destroy: function(successCallback, errorCallback)
{
var options = { wait: true };
var model = this;
successCallback = successCallback || function() {};
errorCallback = errorCallback || function() {};
var destroy = function()
{
model.trigger('destroy', model, model.collection, options);
};
options.success = function(data)
{
if ('SUCCESS' === data.responseCode)
{
if (options.wait || model.isNew())
destroy();
successCallback(data);
if (!model.isNew())
model.trigger('sync', model, data, options);
}
else
{
errorCallback(data);
}
};
if (this.isNew())
{
options.success();
return false;
}
var xhr = this.sync('delete', this, options);
if (!options.wait)
destroy();
return xhr;
}

Resources