Ionic- Angular Js - Store array locally - javascript

Hello I am developing an Ionic app and I have an array that I want to push items on to it, but not lose the data when I change screens. Also, I do not want to use a database. Is there any other way? to add to an existing array and store that array locally?
$scope.tasksCollection = [
{ info: 'Go studying', measured: 'no', total: 1, done: 1, id: 1 },
{ info: 'Go to the beach', measured: 'no', total: 1, done: 1, id: 2},
{ info: 'Run', measured: 'yes', total: 30, done: 15, id: 3}
];
$scope.tasksCollection.push({
info: $scope.taskInfo,
measured: $scope.result,
total: total,
done: 0,
id: $scope.tasksCollection.length
})
The add function is working perfectly I just loose the data when changing states.

If you want to keep data between controllers either use a service or local storage if you want to keep the data even when you quit the app.
Service example
Further angular documentation regarding services: https://docs.angularjs.org/guide/services
service.js:
angular.module('yourmodule.services')
.service('Tasks', [function () {
var collection = {
tasks: []
};
return {
getTasks : function(){ return collection.tasks; }
}
}]
);
controller.js
angular.module('yourmodule.controllers')
.controller('TaskCtrl', ['$scope', 'Tasks',
function($scope, Tasks){
$scope.Tasks = Tasks //Expose service to template
$scope.addTask = function(){
Tasks.getTasks().push({name : 'a new task'});
}
}]);
Local storage example
This is an excellent library which provides easy localstorage access for angularjs: https://github.com/grevory/angular-local-storage
angular.module('yourmodule.controllers')
.controller('TaskCtrl', ['$scope', 'localStorageService',
function($scope, localStorageService){
$scope.collection = {
tasks : localStorageService.get('tasks') || [];
}
$scope.addTask = function(){
$scope.collection.tasks.push({name : 'a new task'});
localStorageService.set('tasks', $scope.collection.tasks);
}
}]);

How about HTML5's locaStorage?
See Ionic formulas on Using Local Storage.

Related

Show the Pos User only the Contacts she has created | Odoo - models.JS

Odoo 14 is an open source erp system. I want to customize the Point of Sale module but as a rookie I couldn't do it.
Odoo uploads and presents all customers to all pos users. I want to fetch only contacts created by POS users, not all customers.
https://github.com/odoo/odoo/blob/14.0/addons/point_of_sale/static/src/js/models.js#L221
model: 'res.partner',
label: 'load_partners',
fields: ['name','street','city','state_id','country_id','vat','lang',
'phone','zip','mobile','email','barcode','write_date',
'property_account_position_id','property_product_pricelist'],
loaded: function(self,partners){
self.partners = partners;
self.db.add_partners(partners);
I added one line as domain filter..
model: 'res.partner',
label: 'load_partners',
fields: ['name','street','city','state_id','country_id','vat','lang',
'phone','zip','mobile','email','barcode','write_date',
'property_account_position_id','property_product_pricelist'],
**domain: function(){ return [['create_uid', '=', 'pos_session.id']]; },**
loaded: function(self,partners){
self.partners = partners;
self.db.add_partners(partners);
But doesn't work.
domain: function(){ return [['create_uid', '=', 2]]; } or 3,4,5 is working.The pos user with the 2,3,4 id number can see the customers she has created.. I don't know how to get the id of the pos user..I would be glad if you help.
Have you tried using "pos.session.id" or "pos.session.user_id" instead of "pos_session.id"?
if it doesn't work try replacing the string with self.session.id or self.session.user_id
I hope this would solve the issue.
I think the code may be like this:
{
model: 'res.partner',
label: 'load_partners',
domain: function(){ return [['create_uid', '=', self.session.id]]; }
fields: ['name','street','city','state_id','country_id','vat','lang',
'phone','zip','mobile','email','barcode','write_date',
'property_account_position_id','property_product_pricelist'],
loaded: function(self,partners){
self.partners = partners;
self.db.add_partners(partners);
}
}
You can use the session.uid.
Example:
domain: function(self){ return [['create_uid', '=', self.session.uid]]; },

AngularJS localstorage for a factory

I am a newbie to IonicFrameWork and was following their "starter tab" template and made a few modifications to "delete" and "bookmark" items from a factory.
My books.js which contains the factory looks as follow:
.factory('Books', function() {
// books data
var books = [{
id: 0,
title: 'Sample Title',
author: 'Sample Author',
category: 'Horor, Fiction',
cover: '/cover.jpeg',
details: 'some details about the book',
chapters: [
{
id : 1,
name: 'Chapter 1',
filename: 'chapter1.html',
},
{
id : 2,
name: 'Chapter 2',
filename: 'Chapter2.html',
}
]
}
.....
return {
all: function() {
return books;
},
// remove a book from the list
remove: function(book) {
books.splice(books.indexOf(book), 1);
},
and my controllers.js looks like this:
....
.controller('DashCtrl', function($scope, Books) {
$scope.books = Books.all();
$scope.remove = function(book) {
Books.remove(book);
};
})
.controller('singlebookCtrl', function($scope, $stateParams, Books){
$scope.book = Books.get($stateParams.bookId);
$scope.toggleIcon = function ($evemt, iconName, book){
var buttonClasses = $event.currentTarget.className;
// add the book to favorite
if (....){
book.isFavorite = true;
}
// remove the book from favorite
else {
book.isFavorite = false;
}
....
when I exit the app and open it again, the deleted item is back and favorite items are gone.
When searching for a solution , I came across this article which states I should use window.localstorage. But not sure how I should apply this method for a factory.
I personnaly prefer using ngStorage that makes it very simple and straight forward to use localStorage & sessionStorage.
For example, after injecting the dependency in your controller you can:
Set a variable :
$scope.favList = [1, 4, ...]
$scope.jsonList = { ... }
$localStorage.favLists = $scope.favList;
$localStorage.jsonList = $scope.jsonList;
Access a variable, Simply access to localStorage value :
var favList = $localStorage.favLists;
For all intents and purposes you can treat Local Storage just as if it were a key/value store, like a javascript object. So if you want to save a value in local storage, just do it like the following.
window.localStorage["bookOne"] = "STRING HERE"
Or if you want to save a javascript object:
window.localStorage["bookOne"] = JSON.stringify({a:b})
And it should persist between page reloads.
The real issue here is that in your code, you are setting books on each load with var books = .... Every time you reload the application it will re-apply books and favourites will be lost. So beyond just saving it to window.localStorage you will also have to read from local storage and assign it to your books and favourites variables when your app loads in order to see the changes that were previously made.
You can simply do it with angular-local-storage module, here's some example based on your problem.
angular.module('app', ['LocalStorageModule'])
.factory('Books', function(localStorageService) {
// favorites list(books id)
var favList = [1, 2, 3, ...];
// ....
return {
remove: function(id) {
favList.splice(favList.indexOf(id), 1);
// sync with localStorage
localStorageService.set(favorites, favList);
},
// ....
}
});
Note that you can simply use angular-local-storage#bind and bind specific scope-key to this service that automatically do this synchronisation for you. for example:
// Inside your controller
$scope.favList = [1, 4, ...]
// returns a deregistration function for this listener.
$scope.unbind = localStorageService.bind($scope, 'favList');

Angular JS and Store DB like persistance

I've got an AngularJS app with a movies array in my controllers.
app.controller("MoviesListCtrl", ["$scope",
function($scope) {
$scope.movies = [
{
id:1,
originalTitle:'Gone with the Wind',
year: 2008
},
{
id:2,
originalTitle:'Back To The Future',
year: 1988
}
];
$scope.addMovie = function(){
$scope.movies.push({
id:3,
originalTitle: 'Mitchell and Jackie'
})
};
}
]);
I'd like to simply store these objects on a database, and be able to find them by their properties. I'm using node-webkit, and about data storage, the developer gives the example of StoreDB (https://github.com/rogerwang/node-webkit/wiki/Save-persistent-data-in-app - https://github.com/djyde/StoreDB/blob/master/README_EN.md).
I find StoreDB really simple, and it seems to fit my needs. But how can I bind it with Angular ? Have you got an equivalent made for Angular ?
Thank you

Make ember to resolve hasMany relationship when loading

I'm currently facing a big problems for days. I'm using ember simple-auth plugin which provide me a session object accessible through the code or the templates. That session object store the account information such as username, id and rights.
My models are like this :
App.Right = DS.Model.extend({
label: DS.attr('string', { defaultValue: undefined })
});
App.Right.FIXTURES = [
{
id: 1,
label: 'Admin'
}, {
id: 2,
label: 'Manager'
}, {
id: 3,
label: 'User'
}
];
App.User = DS.Model.extend({
username: DS.attr('string'),
rights: DS.hasMany('right', {async: true})
});
App.User.FIXTURES = [
{
id: 1,
username: "Someone",
rights: [1]
}
];
Then I have (as specified on the simple-auth documentation) this setup :
App.initializer({
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.Session.reopen({
account: function() {
var userId = this.get('userId');
if (!Ember.isEmpty(userId)) {
return container.lookup('store:main').find('user', userId);
}
}.property('userId')
});
...
}
});
Inside one of my view I'm doing this:
this.get('context.session.account.rights').toArray()
but it gives me an empty array. That piece of code is executed inside an Ember.computed property.
The question is how can I resolve the childrens of account before rendering the view ?
Since async: true this.get('context.session.account.rights') will return a promise object so you will have to use this.get('context.session.account.rights').then(... see: http://emberjs.com/api/classes/Ember.RSVP.Promise.html#method_then
Okay so I finally got it to work. It doesn't solve the original question because the original question was completely stupid. It's just IMPOSSIBLE to resolve relationships synchronously when you use the async: true. Trying to resolve it in advance is NOT the solution because you will still not know when it has actually resolved.
So here is the solution:
$.each(this.get('cellContent.buttonList'), function(i, button) {
button.set('hasAccess', false);
this.get('context.session.account').then(function(res) {
res.get('rights').then(function(result) {
button.set('hasAccess', Utils.hasAccess(result.toArray(), button.rights));
});
});
});
Using the following cellContent.buttonList definition:
buttonList: [
Ember.Object.create({
route: 'order',
label: 'Consult',
rights: 'all'
}), Ember.Object.create({
route: 'order.edit',
label: 'Edit',
rights: [1, 2]
})
]
Explanation
We have to use Ember.Object in order to have access to the set method. Using an Ember object is very handy. It allows us to change the value of properties after the render process making the view to update according to the new value you just set.
Because it updates the view, you don't have to care anymore whether your model has resolved or not.
I hope this will help people as much as it helps me.

Angular factory not loading data

I'm trying to move http calls to angular factory but not sure why data not loaded. The issue is related to the customersController, for now I load data locally but eventually will move it to $http
app.factory('apiFactory', ["apiFactory", "$http", (apiFactory, $http) ->
factory = {}
customers = [
{ name: 'Apple', city: 'Cupertino' },
{ name: 'Google', city: 'SF' }
]
factory.getCustomers ->
customers
])
Here is Plunker http://plnkr.co/edit/itYnyzg2uS5xc6MJIIkE?p=preview
Because you were facing a circular reference.
You don't need apiFActory while defining apiFactory, hence circular reference.
Factory/Service should produce an API to be used by controller
Pardon my coffee script, if I am wrong anywhere. I tried to co-relate it to JavaScript for the API method. I may be wrong with the sytnax.
app.factory('apiFactory', ["$http", ($http) ->
factory = {}
customers = [
{ name: 'Apple', city: 'Cupertino' },
{ name: 'Google', city: 'SF' },
{ name: 'Mont Blanc', city: 'Paris' }
]
return {
getCustomers: () ->
customers
}
])
Refer this modified version of PLUNKR

Categories

Resources