I'm retrieving datapoints by mongoose from a collection of the form:
{
"_id":"1",
"creator":
{"_id":"a",
"username":"aaa",
"name":"aaa"},
"comment":"",
"value":10,
"created":"2016-05-28T12:09:25.666Z"},
{
"_id":"2",
"creator":
{"_id":"b",
"username":"bbb",
"name":"bbb"},
"comment":"",
"value":100,
"created":"2016-05-28T09:13:18.361Z"}
...
Where each datapoint is defined by a Schema and creator is defined by a separate Schema.
I'm able to retrieve all datapoints via angular by using the resource query method:
$scope.find = function() {
$scope.datapoints = Datapoints.query();
};
I would now like to retrieve only those datapoints corresponding to the specific user (whose details are accessible through $scope.authentication.user).
Failed attempts include:
$scope.findByUser = function() {
user = $scope.authentication.user;
$scope.datapoints = Datapoints.query({creator:user});
};
or:
$scope.findByUser = function() {
Datapoints.query(function(result) {
$scope.datapoints = $filter('filter')(result, {creator: $scope.authentication.user});
});
or:
$scope.findByUser = function() {
$scope.datapoints = Datapoints.query();
$scope.datapoints = $filter('filter')($scope.datapoint, {creator: $scope.authentication.user});
};
Any help is appreciated. Thanks!!
Related
I am using bramski/angular-indexedDB in my application. Basic CRUD operations are working fine, but the custom queries are not working as expected.
I am using the code
angular.module('myModuleName', ['indexedDB'])
.config(function ($indexedDBProvider) {
$indexedDBProvider
.connection('myIndexedDB')
.upgradeDatabase(1, function(event, db, tx){
var objStore = db.createObjectStore('people', {keyPath: 'ssn'});
objStore.createIndex('name_idx', 'age', {unique: false});
objStore.createIndex('name_idx, age_idx', ['name', 'age'] , {unique: false});
});
Basic query operations are working like follows
$indexedDB.openStore('people', function(x){
var find = x.query();
find = find.$eq('John');
find = find.$index("name_idx");
x.eachWhere(find).then(function(e){
$scope.list= e;
});
});
which results following query.
select * from people where name='John'
But, in the above scenario how we can execute custom quires like
select * from people where name='John' and age='25';
delete from people where name='John' and age='25';
The library you are using doesn't have complex queries, however you can write a pure-js solution for it, similar to this:
First you need to define your index as:
objStore.createIndex('name_age_idx', ['name', 'age'] , {unique: false});
Then you can have a search query for only those values that match the search result
searchIndexedDB = function (name, age, callback) {
var request = indexedDB.open(dbName);
request.onsuccess = function(e) {
var db = e.target.result;
var trans = db.transaction(objectStoreName, 'readonly');
var store = trans.objectStore(objectStoreName);
var index = store.index('name_age_idx');
var keyRange = IDBKeyRange.only([name, age]);
// open the index for all objects with the same name and age
var openCursorRequest = index.openCursor(keyRange);
openCursorRequest.onsuccess = function(e) {
let result = e.target.result;
// first check if value is found
if(result){
callback(result.value); // your callback will be called per object
// result.delete() - to delete your object
result.continue(); // to continue itterating - calls the next cursor request
}
};
trans.oncomplete = function(e) {
db.close();
};
openCursorRequest.onerror = function(e) {
console.log("Error Getting: ", e);
};
};
request.onerror = myStorage.indexedDB.onerror;
}
If you need a range from and too index, all you need is change the keyrange to:
var keyRange = IDBKeyRange.bound([name,fromAge], [value, toAge]);
I am trying to create a service which holds values that I want to be able to update from other controllers. It's a fake financial tracker which allows me to update the values in this service. I can't get it to work and I know I may be setting it up incorrectly. Can someone help me out with this?
My code:
(function () {
"use strict";
var Bkbank = angular.module('Bkbank' []);
Bkbank.controller('dashboardCtlr', function ($scope, dashboardSrvs) {
/*User Data*/
$scope.userName = dashboardSrvs.userName;
$scope.acctNum = dashboardSrvs.acctNum;
$scope.startDate = dashboardSrvs.startDate;
$scope.checkingsTotal = dashboardSrvs.checkingsTotal;
$scope.savingsTotal = dashboardSrvs.savingsTotal;
$scope.investTotal = dashboardSrvs.investTotal;
$scope.ouncesUpdate = dashboardSrvs.ouncesUpdate;
$scope.debtBalance = dashboardSrvs.debtBalance;
$scope.goldSpot = dashboardSrvs.goldSpot;
/*Section Titles*/
$scope.userTitle = dashboardSrvs.userTitle;
$scope.servicesTitle = dashboardSrvs.servicesTitle;
$scope.checkingsTitle = dashboardSrvs.checkingsTitle;
$scope.savingsTitle = dashboardSrvs.savingsTitle;
$scope.investTitle = dashboardSrvs.investTitle;
$scope.debtTitle = dashboardSrvs.debtTitle;
$scope.savingsUpdateTitle = dashboardSrvs.savingsUpdateTitle;
});
Bkbank.service('dashboardSrvs', function () {
/*User Data*/
this.userName = "Tim Willson";
this.acctNum = 554887;
this.startDate = "01/12/75";
this.checkingsTotal = "56458.00";
this.savingsTotal = "98187.00";
this.investTotal = "34143.00";
this.ouncesUpdate = "30";
this.debtBalance = "10000.00";
this.goldSpot = "1138.10";
/*Section Titles*/
this.userTitle = "User";
this.servicesTitle = "Financial Services";
this.checkingsTitle = "Checkings";
this.savingsTitle = "Savings";
this.investTitle = "Investments";
this.debtTitle = "debt";
this.savingsUpdateTitle = "Update Savings Account";
});
}());
I am not fully clear with the question you have asked but what I understood is you want to get/set attribute values into service so that updates available to all the consumer controller(s). In such scenario you can create service as e.g.
app.service('dashboardSrvs', function() {
var userName = "Tim Willson"; //Set some default Value
return {
get userName() {
return userName;
},
set userName(val) {
userName = val;
}
}
});
And inside the controller you can update the userName as -
testService.userName = 'Mike Tyson';
Angular merge to the rescue!
I advise you in advance to read this great article about Angular copy / extend / merge objects. Article link here
var demoApp = angular.module("demoApp", []);
demoApp.service("dashboardService", function () {
var configObj = {
"userData": {
"userName": "A",
"acctNum": "B",
"startDate": "C"
}
};
return configObj;
});
demoApp.controller("appController", function ($scope, dashboardService) {
// Override the new values of the service with a new object
var newConfigValues = {
"userData": {
"userName": "X",
"acctNum": "Z"
}
};
var newConfigObj = angular.merge({}, dashboardService, newConfigValues);
console.log(newConfigObj); // "userName": "X", "acctNum": "Z", "startDate": "C"
});
As you can see, you can override all or just some values. If you do the latter, the original values in your service will be kept.
JSFiddle here
I'm searching through clients invoices
These invoices are stored within the client json.
so...
clients: {
... : {
invoices: {
},
},
}
I'm doing this by this:
var ref = new Firebase(fbUrl+'/clients/'+client+'/invoices/');
ref.on("value", function(snapshot) {
var list = snapshot.val();
angular.forEach(list, function(item) {
if(item.settings.number == id)
{
console.log(item.id());
invoice.details = item;
}
})
});
Inside the "if" how do I get the unique id auto generated by Firebase? In your html your able to do $id typically.
Once you call snapshot.val(), you're just dealing with a Javascript object. See the documentation for angular.forEach. You just need to specify a second argument to the function.
angular.forEach(list, function(item, key) {
...
});
Here is the problem,
Server responds with several records in JSON, which number is greater than grid pageSize parameter specified in the Store. The total number is not returning by a server in this JSON with data. The number of such records is known and could be different (this number should be requested from the server in another request). The total number is needed for the pagingtoolbar.
How to tell the proxy reader this number from the view controller?
The only workable solution I found is to override the Ext.data.reader.Json reader with the following code:
Ext.define('MyApp.custom.AnotherReader',{
extend: 'Ext.data.reader.Json',
alias : 'reader.anotherReader',
// разбираем ответ и записываем в store
getResponseData : function(response) {
var st = Ext.decode(response.responseText);
st.total = 5;
//console.log(st);
return st;
}
});
The problem is I cannot dynamically change this total parameter from the viewcontroller.
JSON 1:
[
{
"id":"1",
"user_id":"11",
},
{
"id":"2",
"user_id":"12",
},
{
"id":"3",
"user_id":"13",
},
{
"id":"4",
"user_id":"14",
},
{
"id":"5",
"user_id":"15",
}
]
JSON 2:
{
"records_count": "5"
}
You can do this inside your controller -
// some event handler/ or normal function inside your Controller that you'll call
somFunction: function() {
var me = this;
var store = Ext.getStore(<storeId>); // you can even pass the store
//instance as a parameter to this function
var reader = store.getProxy().getReader();
Ext.override(reader, {
getResponseData : function(response) {
var st = Ext.decode(response.responseText);
st.total = me.getValueYouWant();
return st;
}
});
}
So I am trying storing product types from a json file before trying to add them to a collection but am getting some strange results (as in I dont fully understand)
on my router page i setup a variable for cached products as well as product types
cachedProductTypes: null,
productType : {},
products : {},
getProductTypes:
function(callback)
{
if (this.cachedProductTypes !== null) {
return callback(cachedProductTypes);
}
var self = this;
$.getJSON('data/product.json',
function(data)
{
self.cachedProductTypes = data;
callback(data);
}
);
},
parseResponse : function(data) {
result = { prodTypes: [], products: [] };
var type;
var types = data.data.productTypeList;
var product;
var i = types.length;
while (type = types[--i]) {
result.prodTypes.push({
id: type.id,
name: type.name,
longName: type.longName
// etc.
});
while (product = type.productList.pop()) {
product.productTypeId = type.id,
result.products.push(product);
}
};
this.productType = result.prodTypes;
console.log( "dan");
this.products = result.products;
},
showProductTypes:function(){
var self = this;
this.getProductTypes(
function(data)
{
self.parseResponse(data);
var productTypesArray = self.productType;
var productList=new ProductsType(productTypesArray);
var productListView=new ProductListView({collection:productList});
productListView.bind('renderCompleted:ProductsType',self.changePage,self);
productListView.update();
}
);
}
when a user goes to the show product types page it runs the showProductsType function
So I am passing the products type array to my collection
on the collection page
var ProductsType=Backbone.Collection.extend({
model:ProductType,
fetch:function(){
var self=this;
var tmpItem;
//fetch the data using ajax
$.each(this.productTypesArray, function(i,prodType){
tmpItem=new ProductType({id:prodType.id, name:prodType.name, longName:prodType.longName});
console.log(prodType.name);
self.add(tmpItem);
});
self.trigger("fetchCompleted:ProductsType");
}
});
return ProductsType;
now this doesnt work as it this.productTypesArray is undefined if i console.log it.
(how am I supposed to get this?)
I would have thought I need to go through and add each new ProductType.
the strange bit - if I just have the code
var ProductsType=Backbone.Collection.extend({
model:ProductType,
fetch:function(){
var self=this;
var tmpItem;
//fetch the data using ajax
self.trigger("fetchCompleted:ProductsType");
}
});
return ProductsType;
it actually adds the products to the collection? I guess this means I can just pass an array to the collection and do not have to add each productType?
I guess this means I can just pass an array to the collection and do not have to add each productType?
Yes, you can pass an array to the collection's constructor, and it will create the models for you.
As far as your caching code, it looks like the problem is here:
if (this.cachedProductTypes !== null) {
return callback(cachedProductTypes);
}
The callback statement's argument is missing this - should be return callback(this.cachedProductTypes).