Save the value of a service in a variable - angularjs

I must fill a combo to be able to select the value that the user wanted I have managed to do this with the data stored in an array, the next step is to consult a service and use the return values
<html>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="text">ObjectType:</label>
<input type="text" ng-model="type" ng-keyup="complete(type)" class="form-control" placeholder="Search"/>
<ul class="list-group">
li class="list-group-item" ng-repeat="data in filterType" ng-click="fillTextbox(data)">{{data}}</li>
</ul>
</div>
</div>
</html>
var app = angular.module("Trace", []);
app.controller('TraceControlles', function ($scope, $http) {
//$scope.typeList = ["integration", "none"];
$scope.typeList = [];
$scope.loadTypes = function () {
$http.get("/api/Trace/GetObjectType")
.then(function (responce) {
$scope.typeList = responce.data;
}, function errorCallback(responce) {
});
}
$scope.complete = function (string) {
var output = [];
angular.forEach($scope.typeList, function (type) {
if (type.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
output.push(type);
}
});
$scope.filterType = output;
}
$scope.fillTextbox = function (string) {
$scope.type = string;
$scope.filterType = null;
}
});
146/5000
When running the web api the service return values are not loaded, the browser does not mark any syntax error or anything like that.

Related

Error while retrieving data from local storage

i am unable to retreive the data when i reopen my app.What should i do to permanently save the data
I tried this code:
<body ng-app="starter" ng-controller="Appctrl">
<form data-ng-submit="addTodo()" class="todo-form">
<input type="text" data-ng-model="todoText" placeholder="Enter new ToDo
item" />
<br />
<input type="submit" value="Add Task" />
</form>
<ul class="unstyled">
<li data-ng-repeat="item in todo track by $index">
<input type="text">
<span>{{ item.text }}</span>
</li>
</ul>
</body>
and in app.js:
.controller("Appctrl", function($scope) {
$scope.addTodo = function() {
$scope.text = $scope.todoText;
$scope.todos = [];
$scope.todo.push(text);
$scope.todoText = ''; //clear the input after adding
localStorage.setItem('todo', JSON.stringify($scope.todo));
$scope.saved = localStorage.getItem('todo');
localStorage.setItem('todo', JSON.stringify($scope.saved));
};
});
When retrieving the data from local storage check for existence then JSON.parse(localStorage.getItem('todo')) the get from local storage
In your case:
//you will need to parse the string to store it as an object
$scope.saved = JSON.parse(localStorage.getItem('todo'));
You can use the following factory:
yourApp.factory('$localStorage', ['$window', function($window) {
return {
store: function(key, value) {
$window.localStorage[key] = value;
},
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
storeObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key,defaultValue) {
return JSON.parse($window.localStorage[key] || defaultValue);
}
}
}]);
To use the factory you should inject it in your controller and use it like the following:
//to store
$localStorage.storeObject("sometoken", data);
//to retrieve
$localStorage.getObject("sometoken", "");
i solved my issue:
.controller("Appctrl",function($scope){
$scope.saved = localStorage.getItem('id');
$scope.id = JSON.parse($scope.saved);
localStorage.setItem('id', JSON.stringify($scope.id));
$scope.addTodo = function() {
//$scope.text=$scope.todoText;
$scope.id = [];
$scope.id.push({text:$scope.idText});
$scope.idText = ''; //clear the input after adding
localStorage.setItem('id', JSON.stringify($scope.id));
};
});
Check your code in controller.
You are doing : $scope.todo.push(text); instead of $scope.todos.push(text); itseems

View results of a search in the same View AngularJS

First sorry for my bad english. I'm developing an app to be able to study and was putting everything on the controller, all queries and all. But then I decided to pass it to a service (vi which is the right to do so), only when I queries for my search service just stopped working.
In the template I list all registered categories and it has an input, which makes the search all registered establishments in the DB. I wish that when you do a search, the list simply update with a new, only listing the results of this search.
When I try to do a search, the following error appears:
Object {message: "sqlite3_bind_null failure: bind or column index out of range", code: 0}
And so are all related to this template code and the search:
Service.js
app.service('Market', function($cordovaSQLite, DBA) {
var self = this;
self.allCategories = function() {
return DBA.query("SELECT id, category_name FROM tblCategories")
.then(function(result){
return DBA.getAll(result);
});
}
self.searchAll = function(nameSearch) {
var parameters = [nameSearch];
return DBA.query("SELECT id, place_name FROM tblPlaces WHERE place_name LIKE '%(?)%'", parameters)
.then(function(result) {
return DBA.getAll(result);
});
}
return self;
})
Controller.js
app.controller('CategoriesCtrl', function($scope, Market) {
$scope.categories = [];
$scope.categories = null;
$scope.items = [];
$scope.items = null;
var nameSearch = '';
$scope.searchkey = '';
$scope.myClick = function (search) {
nameSearch = search;
console.log(nameSearch);
$scope.searchResult = function(nameSearch) {
Market.searchAll(nameSearch).then(function(items) {
$scope.items = items;
console.log(items);
});
}
$scope.searchResult();
};
$scope.listAllCategories = function() {
Market.allCategories().then(function(categories) {
$scope.categories = categories;
});
}
$scope.listAllCategories();
})
Categories.html
<div class="bar bar-header item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-ios-search placeholder-icon"></i>
<input type="text" placeholder="Search" name="key" autocorrect="off" ng-model="searchkey">
</label>
<button class="button" ng-click="myClick(searchkey)">Buscar</button>
</div>
<ion-list>
<ion-item ng-repeat="category in categories">{{category.category_name}}</ion-item>
</ion-list>

md-checkbox does not work with ng-click

I want to save position each time when I change checkbox:
<h1 class="md-display-2">Simple TODO ng app</h1>
<h2 class="md-display-3"></h2>
<div ng-include src="'todo/add.html'"></div>
<div>
<div layout="row">
<div flex class="md-title">Scope</div>
<div flex="10" class="md-title">Till date</div>
<div flex="10" class="md-title">Is reached?</div>
<div flex="10" class="md-title">
<span ng-click="todoctrl.show_add()" class="material-icons controls">add</span>
</div>
</div>
<div layout="row" ng-repeat="todo in todoctrl.todos track by $index">
<div flex ng-class="{true:'striked', false:'simple'}[todo.reached]">{{todo.name}}</div>
<div flex="10">
{{todo.tillDate | date:'dd/MM/yyyy'}}
</div>
<div flex="10">
<md-checkbox ng-model="todo.reached" aria-label="Is reached" ng-click="todoctrl.changeState(todo.name)"></md-checkbox>
</div>
<div flex="10">
<span ng-click="todoctrl.deleteScope(todo.name)"
class="material-icons controls">clear</span>
</div>
</div>
</div>
In this case controller is touched (I tried with to debug with console log), but the checkbox value is not changed before page reload. After reload the value is checkbox is presented as expected.
If I remove ng-click="todoctrl.changeState(todo.name)" then checkbox is working good, but no info is sent to controller.
This is my service:
(function() {
'use strict';
angular.module('app').service('ToDoService', ToDoService);
ToDoService.$inject = ['JsonService'];
function ToDoService(JsonService) {
return {
deleteScope : deleteScope,
submitScope : submitScope,
changeState : changeState,
getData : getData
}
function getData() {
var todos = JsonService.getData();
return todos;
}
function deleteScope(arr, scope) {
arr.splice(findElementByScope(arr, scope), 1);
JsonService.setData(arr);
}
function submitScope(arr, scope, tillDate) {
var newTodo = {};
newTodo.name = scope;
newTodo.reached = false;
newTodo.tillDate = tillDate;
arr.push(newTodo);
JsonService.setData(arr);
}
function changeState(arr, scope) {
console.log("Service change state for scope: " + scope);
var todo = {};
var index = findElementByScope(arr, scope);
todo = arr[index];
todo.reached = !todo.reached;
JsonService.setData(arr);
}
function findElementByScope(arr, scope) {
for (var i = arr.length; i--;) {
if (arr[i].name == scope) {
return i;
}
}
return -1;
}
}
})();
And this is the Controller:
(function() {
'use strict';
angular.module('app').controller('ToDoController', ToDoController);
function ToDoController(ToDoService) {
var vm = this;
vm.show_form = false;
vm.todos = ToDoService.getData();
vm.scope = '';
vm.show_add = show_add;
vm.submitScope = submitScope;
vm.deleteScope = deleteScope;
vm.changeState = changeState;
function show_add() {
console.log("Controller show add");
vm.show_form = true;
}
function submitScope() {
ToDoService.submitScope(vm.todos, vm.scope, vm.tillDate);
vm.show_form = false;
vm.scope = '';
}
function deleteScope(scope) {
ToDoService.deleteScope(vm.todos, scope);
}
function changeState(scope) {
ToDoService.changeState(vm.todos, scope);
}
}
})();
Use ng-change instead of ng-click
<md-checkbox ng-model="todo.reached" aria-label="Is reached" ng-change="todoctrl.changeState(todo.name, todo.reached)"></md-checkbox>
ng-change trigger after value change in model

how to add an object to list an array in angularjs

I am trying to add an object to the existing list. here is my code.
In controller:
$scope.itemList = [];
$scope.itemList = function () {
return itemService.getItemList();
};
getItemList read from a jason file locally not from service. now I am trying to add new object to this list.
here is my view:
<div>
<img src="/icon1.png" ng-click="sendNewItem()">
<input type="text" ng-model="itemtosend.itemName"/>
<input type="text" ng-model="itemtosend.itemNo"/>
</div>
In controller:
$scope.sendNewItem = function(){
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
$scope.itemList = $scope.itemList.push(newItem)
}
but Iam getting push is not a function. how to add the new object to the existing itemList?
You have many problems in your code :
//You define itemList as an Array (so you can push() in it)
$scope.itemList = [];
//But you redefine it as a function (you cannot push() to a function, ofc..
$scope.itemList = function () {
return itemService.getItemList();
};
then :
$scope.sendNewItem = function(){
//you say newItem is a function, but I guess what you want is an object
var newItem = new function(){
this.itemName = $scope.itemtosend.itemName,
this.itenNo = $scope.itemtosend.itemNo,
}
//$scope.itemList.push(newItem) is enough, no need for list = list.push("b")
$scope.itemList = $scope.itemList.push(newItem)
}
What you should have is :
In controller:
$scope.itemList = [];
$scope.sendNewItem = function(){
var newItem = {
itemName : $scope.itemtosend.itemName,
itenNo : $scope.itemtosend.itemNo
};
$scope.itemList.push(newItem)
}
Please find bellow a code snippet :
var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
$scope.itemList = [];
$scope.sendNewItem = function() {
var newItem = {
name: $scope.itemtosend.itemName,
no: $scope.itemtosend.itemNo
};
$scope.itemList.push(newItem)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="Ctrl">
<label>Name :</label><input type="text" ng-model="itemtosend.itemName" />
<label>No :</label><input type="text" ng-model="itemtosend.itemNo" />
<button ng-click="sendNewItem()">Add</button>
<h3>Item List :</h3>
<div ng-repeat="item in itemList">
name : {{item.name}}, num : {{item.no}}
</div>
</div>

Refresh $scope variables from a service

What is the proper method of refreshing data that is retrieved from a service? I am retrieving a test array from my dataService that I'd like to be automatically updated in my view when my save() method is called. I have commented the line that is supposed to update my $scope variable but yet nothing changes. Should I be wrapping it in $apply()?
The data that is placed into the array that dataService.getActivities() returns is from a cookie (which may or not be relevant).
app.controller("activityCtrl", ["$scope", "dataService", function ($scope, dataService) {
$scope.newActivity = "";
$scope.activities = dataService.getActivities();
$scope.save = function (activity) {
try{
if (activity != "") {
dataService.saveActivity(activity);
$scope.newActivity = "";
$scope.activities = dataService.getActivities(); //HERE
}
} catch (e) {
alert(e);
}
}
}
Here is my view, the array lives in a ng-repeat
<div class="col-xs-12" ng-controller="activityCtrl">
<div class="row text-center">
<form novalidate>
<input type="text" placeholder="Activity name" ng-model="newActivity" />
<input type="submit" value="Add activity" ng-click="save(newActivity)" />
</form>
</div>
<div class="row" ng-controller="activityCtrl">
<div class="col-xs-2"> </div>
<div class="col-xs-6 text-left">
<div class="row" ng-repeat="activity in activities">
<div class="btn btn-default" ng-class="{ active : activity.active }" ng-click="activate(activity)">{{ activity.name }}</div>
</div>
</div>
<div class="col-xs-4 text-left">
sdfas
</div>
</div>
</div>
dataService code:
app.service("dataService", function () {
this.getActivities = function () {
if (docCookies.hasItem("activities")) {
var activities = JSON.parse(docCookies.getItem("activities"));
if (activities.constructor != Array) {
activities = [activities];
}
activities.sort(
function (a, b) {
if (a.name > b.name) { return 1; }
if (b.name < a.name) { return -1; }
return 0;
});
return activities;
}
return [];
}
this.saveActivity = function (activity) {
if (!docCookies.hasItem("activities")) {
docCookies.setItem("activities", [JSON.stringify({ "name": activity, "active": true })], Infinity);
} else {
var activities = this.getActivities();
for (var i = 0; i < activities.length; i++) {
if (activities[i].name == activity) {
throw "Activity already exists";
}
}
activities.push({ "name": activity, "active": false });
docCookies.setItem("activities", JSON.stringify(activities), Infinity);
}
};
});
Zac, your answer should work for you. As another option, I like to broadcast an event whenever my service is updated. In the last line of your saveActivity() function in your service, try broadcasting an event on the rootScope. Inject the $rootScope into your service. Add the following to your save method:
$rootScope.$broadcast('activitiesUpdated');
Then in your controller, inject the $rootScope and add an event handler:
$rootScope.$on('activitiesUpdated', function(event, args){
//Update $scope variable here
});
The answer was to look at the cookie value with a call to $watch instead of the method that returns an object. Added this in my activityCtrl
$scope.$watch(function () {
return docCookies.getItem("activities");
}, function (oldVal, newVal) {
$scope.activities = dataService.getActivities();
});

Resources