saving and retrieving saved checkbox values from local storage in angularjs - angularjs

I am new to angularjs and phonegap. I am trying to build an app where on a page, a user can select a category from say 9 categories. I am putting a checkbox beside each category name for the user to select the categories. After selecting a few categories(by checking the respective checkboxes), the user can press the save button for the categories to be saved. My question is how do I save all those categories and how do I retrieve them?
This is the code I have so far
<!--html code --> <!-- the items here the titles of the categories pulled from a data.js file-->
<div ng-repeat="row in items | partition:3">
<div ng-repeat="item in row"">
<input type="checkbox" ng-model="(item.title)">
<div>{{item.title}}</div>
<ons-button modifier="large" ng-click="savecategories()">Ready</ons-button>
/*angularjs code */
app.controller('categoryController', function($scope) {
$scope.savecategories = function() {
if ($scope.category1)
{
localStorage.setItem('category1', true);
}
else {
localStorage.setItem('category2', false);
if ($scope.category2)
{
localStorage.setItem('category2', true);
}
else {
localStorage.setItem('category2', false);
}
/*and so on */
}
});
I tried to see if it is working by putting this line of code so that I would get an alert but no luck.
var national = localStorage.getItem('category1');
window.alert(national);
I am not sure what I am doing wrong. Any help will be greatly appreciated.

Thank you everyone. I figured it out finally. I just added a function which is called everytime a checkbox is checked or unchecked.
<input type="checkbox" ng-model="item.value" name="item.title" ng-change="savecategories()">
In my js file, I did this:
app.controller('HomeController', function($scope, Data, localStorageService) {
$scope.items = Data.items;
if (localStorageService.get('items')) {
$scope.items = localStorageService.get('items');
}
$scope.SaveCategories = function () {
localStorageService.clearAll();
localStorageService.add('items',$scope.items);
}

Related

Angularjs two way data binding - ngChange

I am working on a project which is having a web form using html and angularjs
the backend using java/spring and db oracle.
My form contains few lists say list1,list2...
list1 get its items from db. As soon as user selects the item in list1 ng-change gets trigger and data for list2 geenrates.That means list2 values depends on list1 ng-change directive.After filling all required fields I am saving the form in db.
Now I am giving user a provison that they can see there filled details . So once they click on "edit" they can see all their details. I am using ng-model to bind the data .All fields are working and binding values form db to the html webform except for list2. Can anyone show how can we achieve this.
I am having some issues with hide/show functionality when user wants to see his request in editable mode. Please suggest some workaround.
<div ng-app="myApp" ng-controller="myCtrl">
<label>List1:</label>
<select ng-model="selectedName" ng-change="getList()" ng-options="item for item in names">
</select>
<br>
<label>List2:</label>
<select ng-model="selectedNcomany" ng-options="item for item in comany">
</select>
<button ng-click="editText()">
Edit
</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
var db = {};
$scope.getList = function(){
if($scope.selectedName == "Linus"){
$scope.comany = ["!","2"];
}
else{
$scope.comany =["0"]
}
}
$scope.editText = function(){
$scope.selectedName = "Linus";
$scope.selectedNcomany = "1";
}
});
</script>
https://jsfiddle.net/31d8cv92/12/
I work in the similar environment we created a service show field which looks like this
angular.module('test').service('showField',showField);
function showField(){
this.showfield = function(fieldData,pagemode){
if(angular.isDefined(fieldData) && fieldData.hasOwnProperty('hide')){
if (fieldData.hide) {
if (fieldData.npi) {
if (pagemode == 'view') {
return false;
}else {
return true;
}
} else {
return false;
}
} else {
return true;
}
}
}
}
We invoke this in our required controllers for view mode and update mode.
**(New to AngularJS)

ng-repeat only updating after clicking another tab or typing in a textbox

I'm pretty new to angular and have been having a bit of a problem in trying to create a basic "to-do" list sort of app.
There are various categories in the sidebar, and the user can click a button that brings up a modal prompting the user for the name of a new category. This name is used to create a new category, which is pushed onto the preexisting array.
However, the new category is only appearing after I start typing in another text-box on the screen or click on another tab.
The code that should be relevant:
var list = this;
$(document).on("click", ".prompt", function(e) {
bootbox.prompt("What do you want your new category to be?", function(result) {
if(result !== null) {
list.addCategory(result);
}
});
});
this.addCategory = function(result) {
if(result.trim() != "") {
var newCategory = new Category(result);
list.categories.push(newCategory);
this.setCategory(newCategory);
}
};
I can't seem to figure out how to post HTML as a code block, but here's the directives used to list out the categories (with categoryCtrl being the controller in question): ng-class="{active: categoryCtrl.isSet(category) }" ng-repeat="category in categoryCtrl.categories" ng-init="categoryCtrl.currCategory = categoryCtrl.categories[0]"
I know that the array is being updated immediately - if I add an alert 'bootbox.alert(list.categories[list.categories.length-1].name)' the alert gives me whatever the input was like it's supposed to. It's just not showing up in the ng-repeat.
Another interesting observations is that the ng-init overrides the this.setCategory(newCategory) - so it seems that when the list does update, it is reverting to its ng-init value.
Other places where I have an ng-repeat of an array, it's updated automatically when something new is pushed onto it. I'm wondering if it may have something to do with the modal/usage of bootbox - everywhere else things are added either by a checkbox or keying something into a textbox on screen, this is the only place where a modal is used.
Here is a working plunker based on your code.
The app looks like below. I initialize an array with dummy data for the example, but an empty array would work too. I used the vm = this syntax similar to what you have. When calling $nbBootbox.prompt it returns a promise so you need to use the then() syntax like below:
var app = angular.module('plunker', ['ngBootbox']);
app.controller('MainCtrl', ['$scope', '$ngBootbox', function($scope, $ngBootbox) {
var vm = this;
vm.name = 'World';
vm.categories = ['Category 1', 'Category 2'];
vm.prompt = function() {
$ngBootbox.prompt('Enter a new category?')
.then(function(result) {
console.log('Prompt returned: ' + result);
vm.categories.push(result);
}, function() {
console.log('Prompt dismissed!');
});
}
}]);
To make your HTML more angular like I changed it to this and also use the ControllerAs syntax:
<body ng-controller="MainCtrl as vm">
<p>Hello {{vm.name}} !</p>
<ul>
<li ng-repeat="c in vm.categories">{{c}}</li>
</ul>
Add Category
</body>
So, the link calls the prompt() function... it opens the modal and if you enter in the category, I push it to the categories array and it is added automatically to the page as a new bullet point in the list of categories.
From the documentation:
$ngBootbox.prompt(msg)
Returns a promise that is resolved when submitted and rejected if dismissed.
Example
$ngBootbox.prompt('Enter something')
.then(function(result) {
console.log('Prompt returned: ' + result);
}, function() {
console.log('Prompt dismissed!');
});
Hope this helps. let us know.

Select all elements when all checkboxes unchecked

I am working on a webpage that would display a list of products with several attributes (color, size, style). I would need that when all checkboxes are unchecked, the page would show all the products, and just when I start checking one the categories will it start filtering the products. Is that possible with checklist-model? Thanks in advance
Yes you can use checklist-model (http://vitalets.github.io/checklist-model/ if you are refreeing this)
Have the code below which will tell you how can you do it just add the filtering logic to it.
Controller code
myApp.controller('MyCtrl', function ($scope) {
//On controller load show all the products
$scope.filters = ['color','style','size'];
$scope.allproducts = [];
$scope.selectedFilters = {
filters: []
};
$scope.applyFilter = function (filters)
{
//Add filtering logic to filter objects from allproducts
//according to filter values in the filters array passed in the function.
//the data will be changed in if filter applied to allproducts array as allproducts in binded in view.
}
$scope.$watchCollection('$scope.selectedFilters.filters', function (newVal, oldVal) {
//If all values are unchecked
if($scope.selectedFilters.filters.length == 0)
{
//Show All products
}
else {
//Show the filtered products
applyFilter($scope.selectedFilters.filters) ;
}
}); });
View code:
<div ng-app="MyApp" ng-controller="MyCtrl">
<label ng-repeat="filter in filters">
<input type="checkbox" checklist-model="selectedFilters.filters" checklist-value="filter"> {{filter}}
</label>
<label ng-repeat="product in allproducts">{{product}}</label>
</div>

How to update ng-repeat after updating array

I have a following controller
app.controller('MainController', function($scope, $interval,$mdToast, $document, $mdDialog,$timeout,$mdDialog) {
var stops=[
{
stopName:"testinput1",
noOfStudents:2
},
{
stopName:"testinput2",
noOfStudents:2
},
{
stopName:"testinput3",
noOfStudents:4
}
];
$scope.list=stops;
$scope.addStop=function(name,noOfstudent){
stops.push({
stopName:name,
noODstudent:noOfstudent
})
$scope.list=stops;
}
});
in my view I have following code,
<md-list id="stopList">
<md-list-item class="md-3-line" ng-repeat="item in list" style="background:rgb(233, 233, 233);margin:10px;padding-left: 10px;position: relative;min-height: 60px;">
<div class="md-list-item-text">
<h3>{{item.stopName}}</h3>
<h4>{{item.noOfStudents}}</h4>
</div>
<div ng-show="deleteIcon" ng-click="showConfirm($event);" class='delete_icon'></div>
</md-list-item>
</md-list>
The issue I am facing is when I add a stop, the ng-repeat list does not get updated. I want the view to be updated as I add a stop. I am taking the user input from angular material dialog.
Data will be updated automatically in view after you update it in controller. What problem (may be ) you are facing is typo in addStop function.
You have used two dots when updating list. >> $scope..list=stops;
You don't need to push to stop
Just direct push to $scope.list
When stop assigned in the list it'll assign reference if one is updated another will also
$scope.list=stops;
Like this
$scope.list.push({
stopName: name,
noODstudent: noOfstudent
})
Here is a plnkr:
http://plnkr.co/edit/HlzxQ9sqbMbxDiraT22z?p=preview
Seems to be working for me
var name = 'l'
var noOfStudents = 5
$scope.addStop=function(){
stops.push({
stopName:name,
noOfStudents:noOfStudents
})
$scope.list=stops;
}
i have used static data but there should not be any problem
Try this
$scope.addStop = function (name, noOfstudent) {
stops.push({
stopName: name,
noODstudent: noOfstudent
});
$timeout(function () {
$scope.list = [];
$scope.list = stops;
}, 0);
};

multiple inputs based on array

My angular experience is basically about 3 days part time, so there's probably something simple I'm missing here.
I'm trying to create a dynamic list of multiple inputs based on an array, which I then want to reference from elsewhere in the app. What I've tried is loading a template from a custom directive, then $compile-ing it.
<input data-ng-repeat="term in query" data-ng-model="term">
My controller contains $scope.query = [""] which successfully creates the first empty input box. But the input box doesn't seem to update $scope.query[0] when I modify it. This means that when I try to create another empty input box with $scope.query.push(""); (from a keypress listener looking for the "/" key) I get a "duplicates not allowed" error.
I've tried manually listening to the inputs and updating scope.$query based on their value, but that doesn't feel very "angular", and results in weird behaviour.
What do I need to do to link these values. Am I along the right lines or way off?
I made a simple jsfiddle showing how to use an angular model (service) to store the data. Modifying the text inputs will also modify the model. In order to reference them somewhere else in your app, you can include TestModel in your other controllers.
http://jsfiddle.net/o63ubdnL/
html:
<body ng-app="TestApp">
<div ng-controller="TestController">
<div ng-repeat="item in queries track by $index">
<input type="text" ng-model="queries[$index]" />
</div>
<br/><br/>
<button ng-click="getVal()">Get Values</button>
</div>
</body>
javascript:
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope, TestModel)
{
$scope.queries = TestModel.get();
$scope.getVal = function()
{
console.log(TestModel.get());
alert(TestModel.get());
}
});
app.service('TestModel', function()
{
var queries = ['box1','box2','box3'];
return {
get: function()
{
return queries;
}
}
});

Resources