How do I save this angularJS to HTML5 localStorage - angularjs

Feel free to tell me to go away (I'm a newbie to angular and javascript), but how would I get started on saving this angularJS to localStorage? Is it something that can be done relatively painlessly by creating a saving function in the add()? I've seen that angular has its own local-storage but can this be done without that? Pen: http://codepen.io/kiddigit/pen/LZVXMV
angular.module('app', []);
angular.module('app').controller("MainController", function(){
var vm = this;
vm.title = 'Movie Database';
vm.searchInput = '';
vm.shows = [
{
title: 'Game of Thrones',
actor: 'Dudes',
year: 2011,
favorite: true
},
{
title: 'Walking Dead',
actor: 'More dudes',
year: 2010,
favorite: false
},
{
title: 'The Goonies',
actor: 'The Coreys',
year: 2002,
favorite: true
},
{
title: 'Firefly',
actor: 'Dunno',
year: 2002,
favorite: false
},
{
title: 'Bullit',
actor: 'McQueen',
year: 2013,
favorite: true
},
];
vm.orders = [
{
id: 1,
title: 'Year Ascending',
key: 'year',
reverse: false
},
{
id: 2,
title: 'Year Descending',
key: 'year',
reverse: true
},
{
id: 3,
title: 'Title Ascending',
key: 'title',
reverse: false
},
{
id: 4,
title: 'Title Descending',
key: 'title',
reverse: true
}
];
vm.order = vm.orders[0];
vm.new = {};
vm.addShow = function() {
vm.shows.push(vm.new);
vm.new = {};
};
});

The browser (the window object) has an object called localStorage, simple as that. If you want to save an object to the local storage you better stringify it first using json.
Example:
// inside your controller:
function saveMovie() {
var selectedMovieString = json.stringify(this.selectedMovie); // for example;
localStorage.setItem("selectedMovie", selectedMovieString);
}

Related

Changed AngularJS value from method does not persist after refresh

I am trying to modify the value of a module value in AngularJS but it does not persist. If I click around the app after its modified its fine but the moment I refresh the page it get returned to the default value. How can I change the value and have it persist while the app is being used.
Here is the value:
;(function() {
angular.module('app.common')
.value('config', {
date: {
dateFormat: 'YYYY-MM-DD',
angularDateFormat: 'yyyy-MM-d',
d3DateFormat: '%Y-%m-%d %I:%M %p'
},
multiLineSelectMode: 'single',
labels: {
success: { single: 'Success', plural: 'Successes' },
warning: { single: 'Warning', plural: 'Warnings' },
danger: { single: 'Danger', plural: 'Dangers' },
dashboard: { title: 'Dashboard', single: 'Dashboard', plural: 'Dashboards' },
operations: { title: 'Operations', single: 'Operation', plural: 'Operations' },
locations: { title: 'Locations', single: 'Location', plural: 'Locations' },
devices: { title: 'Devices', single: 'Device', plural: 'Devices' },
customers: { title: 'Customers', single: 'Customer', plural: 'Customers' },
transactions: { title: 'Transactions', single: 'Transaction', plural: 'Transaction' },
payments: { title: 'Payments', single: 'Payment', plural: 'Payments' },
inventory: { title: 'Inventory', single: 'Inventory', plural: 'Inventories' },
iotCampaigns: { title: 'IoT Campaigns', single: 'IoT Campaign', plural: 'IoT Campaigns' },
marketing: { title: 'Marketing', single: 'Campaign', plural: 'Campaigns' },
incidents: { title: 'Incidents', single: 'Incident', plural: 'Incidents' },
reporting: { title: 'Reporting', single: 'Report', plural: 'Reports' }
}
}
);
})();
and here is where I am trying to modify it from another module/file
;(function() {
angular
.module('app.configuration')
.controller('LabelConfigCtrl', LabelConfigCtrl);
LabelConfigCtrl.$inject = ['config', 'ConfigurationService'];
function LabelConfigCtrl(config, ConfigurationService) {
var vm = this;
vm.labelModel = config.labels;
vm.updateConfig = function() {
config = vm.labelModel; <-- this does not persist if I refresh the page
}
}
})();
vm.labelModel is attached to a big form that modifies the value through ng-model

How to edit cells with backgrid

I am trying an example with backgrid paging. I have to edit a cell content on click of edit button then save the updated cell content to the server. Here iam rendering the buttons using backgrid cell extention but not able to figure it out how to enable a cell for editing on click of the button.
Here is the sample am trying.. In EditCell i have a method editRow in which i have to perform the updation.
Thanks
(function(){
//Namespacing the views collections and models
window.App = {
Models: {},
Views: {},
Collections: {},
Helpers: {}
},
//Template helper to load the template of any id
App.Helpers.template = function(id){
return _.template($('#' + id).html());
}
//Person Model
App.Models.Person = Backbone.Model.extend({});
//Person collection - People
App.Collections.People = Backbone.PageableCollection.extend({
model: App.Models.Person,
state: {
pageSize: 10
},
mode: "client"
});
var personCollection = new App.Collections.People([
{
id: 1,
name: 'Trim',
age: 33,
occupation: 'Dotnet Programmer'
},
{
id: 2,
name: 'Crum',
age: 25,
occupation: 'Developer'
},
{
id: 3,
name: 'Drum',
age: 46,
occupation: 'Designer'
},
{
id: 4,
name: 'Srum',
age: 27,
occupation: 'Java Programmer'
},
{
id: 5,
name: 'Vrum',
age: 24,
occupation: 'Developer'
},
{
id: 6,
name: 'Brum',
age: 29,
occupation: 'Designer'
},
{
id: 7,
name: 'Frum',
age: 33,
occupation: 'Dotnet Programmer'
},
{
id: 8,
name: 'Jrum',
age: 25,
occupation: 'Developer'
},
{
id: 9,
name: 'Lrum',
age: 46,
occupation: 'Designer'
},
{
id: 10,
name: 'Hrum',
age: 27,
occupation: 'Java Programmer'
},
{
id: 11,
name: 'Prum',
age: 24,
occupation: 'Developer'
},
{
id: 12,
name: 'Zrum',
age: 29,
occupation: 'Designer'
}
]
);
var EditCell = Backgrid.Cell.extend({
template: _.template('<button>Edit</button>'),
events: {
"click": "editRow"
},
editRow: function (e) {
e.preventDefault();
//Enable the occupation cell for editing
//Save the changes
//Render the changes.
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
this.delegateEvents();
return this;
}
});
var columns = [{
name: "id",
label: "ID",
editable: false,
cell: Backgrid.IntegerCell.extend({
orderSeparator: ''
})
}, {
name: "name",
label: "Name",
cell: "string"
}, {
name: "age",
label: "Age",
cell: "integer"
}, {
name: "occupation",
label: "Occupation",
cell: "string"
}, {
name: "actions",
label: "Actions",
cell: EditCell
}];
// Initialize a new Grid instance
var grid = new Backgrid.Grid({
columns: columns,
collection: personCollection
});
var paginator = new Backgrid.Extension.Paginator({
collection: personCollection
});
// Render the grid and attach the root to your HTML document
$("#grid").append(grid.render().el);
$("#paginator").append(paginator.render().$el);
})();
the following code solved my problem.. With the below code we can make each cell editable/noneditable depending upon a condition. Still looking for a better approach to Enable editing on edit button click.
(function(){
//Person Model
var Person = Backbone.Model.extend({
});
//Person collection - People
var People = Backbone.Collection.extend({
model: Person
});
var personCollection = new People([
{
id: 1,
name: 'Trim',
age: 33,
occupation: 'Dotnet Programmer'
},
{
id: 2,
name: 'Crum',
age: 25,
occupation: 'Developer'
},
{
id: 3,
name: 'Drum',
age: 46,
occupation: 'Designer'
},
{
id: 4,
name: 'Srum',
age: 27,
occupation: 'Java Programmer'
},
{
id: 5,
name: 'Vrum',
age: 24,
occupation: 'Developer'
},
{
id: 6,
name: 'Brum',
age: 29,
occupation: 'Designer'
},
{
id: 7,
name: 'Frum',
age: 33,
occupation: 'Dotnet Programmer'
},
{
id: 8,
name: 'Jrum',
age: 25,
occupation: ''
},
{
id: 9,
name: 'Lrum',
age: 46,
occupation: ''
},
{
id: 10,
name: 'Hrum',
age: 27,
occupation: 'Java Programmer'
},
{
id: 11,
name: 'Prum',
age: 24,
occupation: 'Developer'
},
{
id: 12,
name: 'Zrum',
age: 29,
occupation: 'Designer'
}
]
);
var MyCell = Backgrid.Cell.extend({
initialize: function (options) {
MyCell.__super__.initialize.apply(this, arguments);
this.listenTo(this.model, "backgrid:edited", this.doSomething);
},
doSomething: function () {
console.log('something');
},
enterEditMode: function () {
this.$el.width((this.$el.outerWidth() - 10) + 'px');
Backgrid.Cell.prototype.enterEditMode.apply(this, arguments);
},
exitEditMode: function () {
this.$el.width(false);
Backgrid.Cell.prototype.exitEditMode.apply(this, arguments);
}
});
var columns = [{
name: "id", // The key of the model attribute
label: "ID", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
// Defines a cell type, and ID is displayed as an integer without the ',' separating 1000s.
cell: "string", //Backgrid.IntegerCell.extend({ tagName: "td style='text-align:left'" })
editable:false,
isEnabled: false
}, {
name: "name",
label: "Name",
// The cell type can be a reference of a Backgrid.Cell subclass, any Backgrid.Cell subclass instances like *id* above, or a string
cell: "string", // This is converted to "StringCell" and a corresponding class in the Backgrid package namespace is looked up
editable:false
}, {
name: "age",
label: "Age",
cell: "string", // An integer cell is a number cell that displays humanized integers
editable: false
}, {
name: "occupation",
label: "Occupation",
cell: MyCell, // A cell type for floating point value, defaults to have a precision 2 decimal numbers
editable: function (c, m) {
if (typeof(c.collection) === 'undefined')
return false;
else
return (c.attributes.age <= 30) ? true : false;
}
}];
// Initialize a new Grid instance
var grid = new Backgrid.Grid({
columns: columns,
collection: personCollection
});
// Initialize a client-side filter to filter on the client
// mode pageable collection's cache.
var filter = new Backgrid.Extension.ClientSideFilter({
collection: personCollection,
fields: ['name']
});
// Render the grid and attach the root to your HTML document
$("#grid").append(grid.render().el);
$("#grid").before(filter.render().el);
})();

Draw map based on selected city in selectbox in angularjs

i have a select box for city which has number of cities getting through ng-options. i need to show the map on the website based on city selected in the selectbox.
this is how i am getting city names
// Code goes here
$scope.data = [{
cities: [{
id: 1,
title: 'Mysore'
}, {
id: 2,
title: 'Bangalore'
}, {
id: 3,
title: 'Delhi'
}, {
id: 4,
title: 'Mumbai'
}],
maps: [{
id: 1,
title: 'Zoo',
city_id: 1
}, {
id: 2,
title: 'Palace',
city_id: 1
}, {
id: 3,
title: 'Beach',
city_id: 4
}]
}];
});
Plunker here https://plnkr.co/edit/r1S1e61H3RfH3uYGYTBP?p=preview
Can anyone please help me.
Move the coordinates to the $scope:
$scope.coordinates = {
lat: 28.620089858889145,
lng: 77.17483520507812
};
And:
<ng-map zoom="13" center="{{coordinates.lat}},{{coordinates.lng}}" ...
Use ng-change on the select:
ng-change="centerCity(citySelect.selectedOption)"
In the centerCity method you can use the geocoder to retrieve the coordinates by city name. Then you simply need to update the variables.
Simple example:
var geocoder = new google.maps.Geocoder();
$scope.centerCity = function(city) {
geocoder.geocode({
'address': city.title
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$scope.$apply(function() {
$scope.coordinates.lat = results[0].geometry.location.lat();
$scope.coordinates.lng= results[0].geometry.location.lng();
});
} else {
console.log('Error');
}
});
};
Demo: https://plnkr.co/edit/WETs0FL0DbPbDn2A77hq?p=preview

angularjs : I have one form it has many fields some of them carrying array to display dropdown. is it wise that we should provider?

I have one form which has 10 to 12 fields which contains dropdown and multi select drop down. I want before my controller function gets called all the fields should filled up. I tried something like this :
var app = angular.module('app', []);
app.config(function ($provide) {
var transactionType = [
{ id: 0, type: 'card', value: 'card' },
{ id: 1, type: 'cash', value: 'cash' },
{ id: 2, type: 'other', value: 'other' }
];
var friends = [
{ id: 0, name: 'A', value: 'A' },
{ id: 1, name: 'B', value: 'B' },
{ id: 2, name: 'C', value: 'C' },
{ id: 3, name: 'D', value: 'D' }
];
var currency = [
{ id: 0, currency: 'USD', value: 'USD' },
{ id: 0, currency: 'INR', value: 'INR' },
{ id: 0, currency: 'EUR', value: 'EUR' },
];
$provide.value('TransactionType', transactionType);
$provide.value('Friends', friends);
$provide.value('Currency', currency);
});
app.controller('MainCtrl', function ($scope, TransactionType, Friends, Currency) {
});
Is this the right way considering that may be in future I have to use http service to get array from DB and to populate on dropdown list?
I'd use a specific type of provider called a Factory instead. If you use promises in your factory when switch to http services you'd only need to change your factory code - the rest of your application will work without code changes!
angular.module('myApp')
.factory('Friend', function ($q) {
return {
list: function() {
var deferred = $q.defer();
deferred.resolve([
{ id: 0, name: 'A', value: 'A' },
{ id: 1, name: 'B', value: 'B' },
{ id: 2, name: 'C', value: 'C' },
{ id: 3, name: 'D', value: 'D' }
]);
return deferred.promise;
}
};
});

kendo ui angularjs grid edit

I'm doing a POC for AngularJS and Kendo UI and I need to know how to save updated data on a kendo grid. I have inline editing enabled but can't hook into kendo UI to get the updated data. I created a fiddle (http://jsfiddle.net/aMz7V/14/) but can't get the jsfiddle to work (sorry this is my first time creating a fiddle), so I have pasted the code below:
JavaScript (controller code):
var myApp = angular.module('myApp', ['kendo.directives']);
myApp.controller("gridCtrl", function($scope) {
$scope.assignments = {};
$scope.assignments.dataSource = new kendo.data.DataSource({
data: [
{ StudentName: "John Smith", HomeWork: 9, HomeWork1: 12 },
{ StudentName: "Kodjo Adu", HomeWork: 5, HomeWork1: 15 },
{ StudentName: "Patrick smith", HomeWork: 10, HomeWork1: 19 },
{ StudentName: "Richard lomax", HomeWork: 8, HomeWork1: 18 },
{ StudentName: "Aglade Bone", HomeWork: 7, HomeWork1: 20 }
],
schema: {
model: {
fields: {
StudentName: { type: "string" },
HomeWork: { type: "number" },
HomeWork1: { type: "number" },
}
}
},
pageSize: 3,
});
$scope.assignments.columns = [
{ field: 'StudentName', title: 'Student Name' },
{ field: 'HomeWork', title: 'Home Work / 10' },
{ field: 'HomeWork1', title: 'Home Work / 20' }
];
});
HTML:
<div ng:app="myApp">
<div ng-controller='gridCtrl'>
<div kendo-grid k-data-source="assignments.dataSource" k-selectable="'row'"
k-pageable='{ "refresh": true, "pageSizes": true }'
k-columns='{{assignments.columns}}' k-sortable="true" k-editable="true" k-toolbar="['save','cancel']"></div>
</div>
</div>
So i figured it out, to handle to the save changes event i needed to do this
k-on-save-changes="saveChanges(kendoEvent)"
and just add the saveChanges function to the $scope in the controller.

Resources