How to query parse.com users through factory Service in AngularJS? - angularjs

Building an cross-platform hybrid app using Parse.com, AngularJS using the Ionic Framework. The user creation and querying works fine when using the simple parse.com code from the docs.
However I have been trying to put the query into a AngularJS service, so that it can be accesses and I can do a ng-repeat to display the returned results in a list.
The code put in place so far is this:
View (search.html):
<div class="row">
<div class="col col-75">
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" placeholder="Search" ng-model="search.queryvalue">
</label>
</div>
<div class="col">
<button class="button button-calm" ng-click="searchnow()">Search</button>
</div>
</div>
<ion-list>
<ion-item class="item-avatar" type="item-text-wrap" ng-repeat="user in users">
<img ng-src="{{userpic}}.png">
<h2>{{user.id}}</h2>
<p>{{user.get('location')}}</p>
</ion-item>
</ion-list>
Controller:
.controller('SearchCtrl', function($scope, $state, $rootScope, parseQueryFactory) {
$scope.search = {};
$scope.users = {};
$scope.searchnow = function () {
$scope.users = parseQueryFactory.searchUsers($scope.search.queryvalue);
};
})
Services:
.factory('parseQueryFactory', function($http) {
var query = new Parse.Query(Parse.User);
var people = {};
return {
searchUsers: function(searchVal){
query.startsWith("username", searchVal); // Search username
query.limit(20);
return query.find({
success: function(people) {
/*var objects = {};
for (var i = 0; i < people.length; i++) {
var object = people[i];
objects = objects + object;
}
console.log(people);
return objects;*/
},
error: function(error) {
return error;
}
});
}
}
})
I have tried a few ways to make this work (using sources like the ionic forum, stackoverflow and Google in general), but I am new to angular and not sure how to go about doing this.
The only thing that works is by putting the following code in the controller (but then I cannot use ng-repeat):
$scope.searchnow = function () {
var queryvalue = $scope.user.queryvalue;
userquery.startsWith("username", queryvalue); // Search username
userquery.limit(20);
userquery.find({
success: function(people) {
for (var i = 0; i < people.length; i++) {
var object = people[i];
console.log("ID: " + object.id + ', username: ' + object.get('username'));
}
}, error: function(error) {
console.log("error");
}
});
};
Has anyone implemented such a service for parse.com?
I have looked around and tried implementations from various people, but nothing seems to work in a way that returns a service like response from which ng-repeat comands can be done.

I believe this might help.
Services:
app.factory('Presentation', function($q) {
var Presentation = Parse.Object.extend(Parse.User, {
// Instance methods
}, {
// Class methods
listByUser : function() {
var defer = $q.defer();
var query = new Parse.Query(this);
query.startsWith("username", searchVal); // Search username
query.limit(20);
query.find({
success : function(aPresentations) {
defer.resolve(aPresentations);
},
error : function(aError) {
defer.reject(aError);
}
});
return defer.promise;
}
});
// Properties
Presentation.prototype.__defineGetter__("location", function() {
return this.get("location");
});
Presentation.prototype.__defineGetter__("pic", function() {
var pic = this.get("pic");
if (pic ==null){
pic = 'img/default.png';
return pic;
}
return pic.url();
});
return Presentation; });
Controller:
app.controller('userController', function( Presentation){
user = this;
Presentation.listByUser().then(function(aPresentations) {
user.list = aPresentations;
}, function(aError) {
// Something went wrong, handle the error
});
});
html:
<div class="row">
<div class="col col-75">
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" placeholder="Search" ng-model="search.queryvalue">
</label>
</div>
<div class="col">
<button class="button button-calm" ng- click="searchnow()">Search</button>
</div>
</div>
<ion-list>
<ion-item class="item-avatar" type="item-text-wrap" ng-repeat="user in users">
<img ng-src="{{user.pic}}">
<h2>{{user.id}}</h2>
<p>{{user.location}}</p>
</ion-item>
</ion-list>
For further reading you can check out 5 Tips for using parse with angularjs by slidebean.

Related

Fetching JSON data from multiple web api methods ($q.all)

I have a simple app with a form. When the form loads I want to call a couple of web api methods to fetch the json data used to initialize the form. The form is working fine with hardcoded data in my factory class. I am unsure how I can make multiple request in that file and is kind of stuck.
The form:
<div class="modal-header" style="text-align:center">
<h3 class="modal-title">Configure</h3>
<div style="margin-top:10px">
<button tabindex="100" class="btn btn-success pull-left" type="submit">Submit</button>
<button class="btn btn-warning pull-right" ng-click="close($event)">Close</button>
</div>
</div>
<div class="modal-body">
<div class="col-sm-6" style="width: 100%;">
<form name="joinForm">
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-3">Symbol</label>
<div class="col-sm-9">
<select ng-model="simulationsettings.symbols" ng- options="key as value for (key,value) in symbols"></select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Interval</label>
<div class="col-sm-9">
<select ng-model="simulationsettings.intervals" ng-options="key as value for (key,value) in intervals"></select>
</div>
</div>
</div>
</form>
</div>
The controller:
mainApp2.controller("moduleConfigformController",
function moduleConfigformController($scope, moduleConfigformService,$uibModalInstance) {
$scope.close = function(e) {
$uibModalInstance.dismiss();
e.stopPropagation();
};
$scope.simulationsettings = moduleConfigformService.simulationsettings;
$scope.symbols = $scope.simulationsettings.symbols;
$scope.intervals = $scope.simulationsettings.intervals;
});
The factory class that holds the (hard coded) data for the form:
mainApp2.factory("moduleConfigformService",
function () {
return {
simulationsettings: {
symbols: {
'symbol1': "symbol1",
'symbol2': "symbol2"
},
intervals: {
'60': "1 minute",
'120': "2 minutes",
'180': "3 minutes"
}
}
}
});
Instead of hard coded values I want to call the server but is pretty stuck after several hours of research and trail and error:
mainApp2.factory("moduleConfigformService",
function () {
function getSymbols() {
return $http.get("/api/getsymbols");
}
function getIntervals() {
return $http.get("/api/getIntervals");
}
return {
simulationsettings: {
symbols : getSymbols()
},
intervals : getIntervals()
}
});
Can you point me in the right direction?
The $http Service doesn't return values. It returns promises. See AngularJS $http Service API Reference - General Usage. Also using promise based APIs from a factory can be a bit tricky. I would suggest writing and debugging the code in the controller and later re-factor to use a factory.
app.factory("moduleConfigformService",
function ($q,$http) {
function getSymbols() {
return $http.get("/api/getsymbols")
.then(function (response) {
return response.data;
});
}
function getIntervals() {
return $http.get("/api/getIntervals")
.then(function (response) {
return response.data
});
}
return {
getSymbols: getSymbols,
getIntervals: getIntervals,
simulationsettings: function () {
var promiseHash = {};
promiseHash.symbols = getSymbols();
promiseHash.intervals = getIntervals();
return $q.all(promiseHash);
}
}
});
Usage
var settingsPromise = moduleConfigformService.simulationsettings();
settingsPromise.then(function(settings) {
$scope.simulationsettings = settings;
}).catch(function(error) {
throw error;
});
If i take a look at your controller, i don't see that you wait for the http request to return an answer.
You should take a look at angularjs promises
In short you have to have to use something like
moduleConfigformService.simulationsettings.then(function (response) {
//doSomeThingWithResponse
})

function not execute in controller and factory

i'm developing an app that should call a controller where there are some functions, because i receive from a server (localhost in this moment) a JSON array with a structure like this:
[{
"day": "17/11/2016",
"time": "09:45"
}, {
"day": "17/11/2016",
"time": "16:50"
}, {
"day": "18/11/2016",
"time": "11:25"
}, {
"day": "18/11/2016",
"time": "12:30"
}, {
"day": "21/11/2016",
"time": "16:10"
}, {
"day": "21/11/2016",
"time": "17:25"
}]
And then i print it in two selects in a form in this way:
SELECT 1:
17/11/2016, 18/11/2016, 21/11/2016
SELECT 2:
09:45, 16:50 OR 11:25, 12:30 OR 16:10, 17:25 based on the choice in the first select
Up to this point there are no problems but now it should execute a function that post the coice of the user to the server but the app doesn't execute it.
This is my code,
SCRIPT.JS
angular
.module('demo', [])
.controller('DefaultController', DefaultController)
.factory('dataService', dataService);
DefaultController.$inject = ['dataService'];
function DefaultController(dataService) {
var vm = this;
getEvents();
function getEvents() {
return dataService.getEvents()
.then(function (data) {
vm.data = data;
return vm.data;
});
}
}
dataService.$inject = ['$http'];
function dataService($http) {
var service = {
getEvents: getEvents
};
return service;
function getEvents() {
var config = {
transformResponse: function (data, headers) {
var result = {
events: [],
schedules: []
};
var events = JSON.parse(data);
var dates = [];
for (var i = 0; i < events.length; i++) {
if (dates.indexOf(events[i].day) === -1) {
var date = events[i].day;
dates.push(date);
result.events.push({
date: date
});
}
result.schedules.push({
date: events[i].day,
time: events[i].time
});
}
return result;
}
};
return $http.get('http://<path>/api/apiTimes.php', config)
.then(getEventsCompleted)
.catch(getEventsFailed);
function getEventsCompleted(response) {
return response.data;
}
function getEventsFailed(error) {
console.error(error);
}
}
}
console.log("fine");
function submit ($http){
console.log("funzione");
var data = {};
console.clear();
var link = 'http://<path>/api/apiFix.php';
var mail = window.localStorage.getItem("mail");
$http.post(link, {giorno: data.giorno, ora: data.ora, mail: mail})
.then(function (res){
console.log("Dentro http.post");
var response = res.data;
console.log(response);
});
}
FORM HTML:
<body ng-app="demo" ng-controller="DefaultController as ctrl">
<form ng-submit="submit()">
<div class="list">
<label class="item item-input item-select">
<div class="input-label">
Giorno:
</div>
<select ng-options="event as event.date for event in ctrl.data.events" ng-model="data.giorno">
<option disabled>Seleziona un giorno </option>
</select>
</label>
</div>
<div class="list">
<label class="item item-input item-select">
<div class="input-label">
Ora:
</div>
<select ng-options="schedule as schedule.time for schedule in ctrl.data.schedules | filter: { date: data.giorno.date}" ng-model="data.ora" ng-disabled="!data.giorno">
<option disabled>Seleziona un orario </option>
</select>
</label>
</div>
</div>
</div><br>
<ul class="list">
<li class="item item-toggle">
&Egrave un'urgenza?
<label class="toggle toggle-assertive">
<input type="checkbox">
<div class="track">
<div class="handle"></div>
</div>
</label>
</li>
</ul>
<div align="center">
<input class="button button-calm" type="submit" name="submit" value="Prenota !">
</div>
</form>
</body>
I have no errors in console but the function "submit" it isn't execute.
How can i solve this problem?
Thank's
You have a couple of errors. You need to fix at least these
On your controller (you will need to inject $http)
DefaultController.$inject = ['dataService', '$http'];
function DefaultController(dataService, $http) {
var vm = this;
vm.submit = function (){
console.log("funzione");
var data = vm.form; // IMPORTANT
console.clear();
var link = 'http://<path>/api/apiFix.php';
var mail = window.localStorage.getItem("mail");
$http.post(link, {giorno: data.giorno, ora: data.ora, mail: mail})
.then(function (res){
console.log("Dentro http.post");
var response = res.data;
console.log(response);
});
};
}
And in your form as I mention in the comment, since you are using the controller as approach you need to include ctrl
<form ng-submit="ctrl.submit()">
And rename your ng-model variables to
ng-model="ctrl.form.ora" //ng-model="data.ora"
ng-model="ctrl.form.giorno" //ng-model="data.giorno"

angularjs $http: server 500 (Internal Server Error) when working with laravel

I have searched many solutions but still cannot work.
it shows me
POST http://localhost/travelAbroad/public/touristsData 500 (Internal Server Error)
what i wanna do is that when i choose the filters, the will change according to the filters you choose. And i use ionic as a frontend framework to make a html5 mobile application.
The following is my code:
//html
<span class="ion-ios-arrow-down button button-icon" ng-click="modal.show()"></span>
...
<ion-list>
<ion-item ng-repeat="tourist in tourists | limitTo:numberOfItemsToDisplay">
<h3>Charge: $#{{tourist.charge}}/h</h3>
</ion-item>
</ion-list>
//filterModal file
<ion-modal-view>
<ion-content>
<form name="filterForm" ng-submit="submitForm()">
<div class="list">
<ion-radio ng-model="filter.want" value="company" name="want">
Want a company for building a house
</ion-radio>
<ion-radio ng-model="filter.want" value="expat" name="want">
Find an expaters
</ion-radio>
<div class="list">
<label class="item item-input item-select">
<select ng-model="filter.location" name="location">
<option value="Xihu" selected>Xihu</option>
<option value="Xiacheng">Xiacheng</option>
</select>
</label>
</div>
<input type="hidden" ng-model="filter.token" name="token" value="{{ csrf_token() }}">
<input type="submit" class="button button-full button-light" value="Create">
</div>
</ion-content>
</ion-modal-view>
//angular controller
.controller('listController', ['$scope','$http','$state','$ionicModal', function($scope, $http, $state,$ionicModal){
$http.get("./touristsData").success(
function(data){
$scope.tourists = data;
$scope.numberOfItemsToDisplay = 3; // number of item to load each time
$scope.addMoreItems = function(){
if($scope.tourists.length>$scope.numberOfItemsToDisplay){
$scope.numberOfItemsToDisplay += 3; // load 20 more items
}
............
});//end of get method
$ionicModal.fromTemplateUrl('./filterModal', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.filter = {};
$scope.submitForm = function(){
if($scope.filter.want == 'company'){
$http({
method : 'POST',
url : './touristsData',
beforeSend: function (xhr) {
var token = $scope.filter.token;
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data : {
location: $scope.filter.location
},
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
$scope.tourists = data;
});
$scope.modal.hide();
}
}
//backend
//laravel route:
Route::match(array('GET', 'POST'), '/touristsData', array(
'uses' => 'UserController#touristsData',
'as' => 'touristsData'
));
//laravel controller:
public function touristsData(){//get
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
//$postdata = json_decode(file_get_contents('php://input'));
if(isset($request->location)){
#$location = $request->location;
$tourists = User::where('block','0')
->where('location', $location)
->orderBy('updated_at', 'desc')
->get();
}else{
$tourists = User::where('block','0')
->orderBy('updated_at', 'desc')
->get();
}
//$touristsPostInfo = Post::where('block','0')->get();
return View::make('frontend.data.touristsData',array('tourists'=>$tourists));
}
//touristsData
echo json_encode($tourists);
Include this in your header:
<meta id="token" name="token" content="{{ csrf_token() }}">
This kind of error is captured on the error log file of your server,
you can login with FTP and get the error.log file to check exactly the line and what is the problem.
$http: server 500 (Internal Server Error)
You're server is expecting a url encoded string and you are sending through an object thus it throws the error.
Update following
data: {
location: $scope.filter.location
}
To
data : $httpParamSerializer({
location: $scope.filter.location
})
You'll need to inject the $httpParamSerializer function.

Why do I need $parent to enable the function in ng-click when using ion-scroll?

I am using the following versions:
Ionic, v1.0.0-beta.14
AngularJS v1.3.6
Route configuration:
myApp.config(function ($stateProvider) {
$stateProvider
.state('manager_add', {
url: '/managers/add',
templateUrl: 'app/components/mdl.role_members/views/add.html',
controller: 'ManagerAddController'
});
});
Controller configuration:
myApp.controller('ManagerAddController', function ($scope, $state, $ionicLoading, $filter, ContactService, ManagersService, RoleRequest, RoleRequestsSentService, ToastrService) {
$scope.role_request = RoleRequest.new();
$scope.showContactSearch = false;
$scope.managers = ManagersService.collection();
$scope.$watchCollection("managers", function( newManagers, oldManagers ) {
if(newManagers === oldManagers){ return; }
$scope.managers = newManagers;
$scope.contactsToBeInvited = getNotInvitedContacts();
});
$scope.contacts = ContactService.collection();
$scope.$watchCollection("contacts", function( newContacts, oldContacts ) {
if(newContacts === oldContacts){ return; }
$scope.contacts = newContacts;
$scope.contactsToBeInvited = getNotInvitedContacts();
});
$scope.contactsToBeInvited = getNotInvitedContacts();
function getNotInvitedContacts() {
var notinvited = [];
angular.forEach($scope.contacts, function(contact) {
if(angular.isObject($scope.managers)) {
var results = $filter('filter')($scope.managers, {member_id: Number(contact.contact_id)}, true);
if (results.length == 0) {
this.push(contact);
}
} else {
this.push(contact);
}
}, notinvited);
return notinvited;
}
$scope.search_contact = "";
$scope.search = function(contact) {
if($scope.search_contact === "" || $scope.search_contact.length === 0) {
return true;
}
$scope.showContactSearch = true;
var found = false;
if(contact.display_name) {
found = (contact.display_name.toLowerCase().indexOf($scope.search_contact.toLowerCase()) > -1);
if(found) { return found; }
}
if(contact.contact.getFullName()) {
found = (contact.contact.getFullName().toLowerCase().indexOf($scope.search_contact.toLowerCase()) > -1);
if(found) { return found; }
}
if(contact.contact.email) {
found = (contact.contact.email.toLowerCase().indexOf($scope.search_contact.toLowerCase()) > -1);
if(found) { return found; }
}
return found;
}
$scope.selectContact = function(contact) {
$scope.search_contact = contact.contact.getFullName();
// TODO: Make dynamic role
$scope.role_request.role_id = 4;
$scope.role_request.email = contact.contact.email;
};
$scope.addRoleMember = function(valid) {
if($scope.role_request.email === "") { return; }
if(!valid) { return; }
$ionicLoading.show({
template: 'Please wait...'
});
RoleRequestsSentService.add($scope.role_request).then(function(roleJsonResponse){
ToastrService.toastrSuccess('Request send', 'We have send an invite to '+ $scope.search_contact +'.');
$ionicLoading.hide();
$state.go('managers');
});
}
});
View configuration:
<ion-view view-title="ManagerAdd" >
<ion-content class="has-header scroll="true">
<div class="content">
<div class="list">
<div class="item item-border">
<p>Some text</p>
</div>
</div>
<form name="managerForm">
<div class="list">
<div class="item item-divider">
Some text
</div>
<div class="item item-border">
<form name="fillForm">
<div class="form-group">
<label class="item item-input item-stacked-label item-textarea">
<span class="input-label border-none">Personal message: <span class="text-red required">*</span></span>
<textarea name="message" ng-model="role_member.message" required></textarea>
</label>
<p ng-show="managerForm.message.$dirty && managerForm.message.$error.required"
class="error-message">Message required!</p>
</div>
<div class="form-group">
<label class="item item-input">
<span class="input-label">Search on name <span class="text-red required">*</span></span>
<input type="text" name="search_contact" ng-model="$parent.search_contact">
</label>
<div class="searchResultBox" ng-show="showContactSearch">
<ion-scroll direction="y" class="scrollArea">
<div class="list">
<a class="item item-border item-avatar pointer" ng-repeat="contact in $parent.filteredContacts = (contactsToBeInvited | filter:search:false)" ng-click="$parent.selectContact(contact)">
<img src="{{ contact.getImage('thumbnail') }}">
<h2>{{contact.getIconName()}}</h2>
<p>City: {{contact.contact.city}}</p>
</a>
</div>
</ion-scroll>
<div class="notFound pointer" ng-hide="filteredContacts.length">
<h3>Nobody found</h3>
<p>You can only search through existing contacts</p>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="form-actions">
<button type="submit" class="button button-block regie-button" ng-click="addRoleMember(registerForm.$valid)">
Sent request
</button>
</div>
</form>
<p class="text-red" style="text-align:center; font-size:14px; font-weight: 400;">* required</p>
</div>
</ion-content>
</ion-view>
As you can see in the view I need to use $parent to the following fields to get it to work:
ng-model="$parent.search_contact"
ng-repeat="contact in $parent.filteredContacts = (contactsToBeInvited | filter:search:false)"
ng-click="$parent.selectContact(contact)"
I really don't understand why this is necessary because the complete view is using the same controller. Does anyone have an idea?
This is a very typical angular scoping issue. Ion-view creates a new child scope and uses prototypical inheritance: https://github.com/angular/angular.js/wiki/Understanding-Scopes
Three are several ways to solve:
always use a dot: https://egghead.io/lessons/angularjs-the-dot
use the 'controller as' syntax: http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/
The problem is the inheritance. Between your controller's scope and those fields, there are several new scopes (ion-content, ion-scroll and probably others).
So for example the ng-model="search_content". When you write in there, it is going to create a search_content variable inside the ion-content scope (or an intermediary scope if there is any that I didn't see). Since search_content is being created inside ion-content, your controller won't see it.
If you do $parent.search_content it will create it in the parent content (AKA the controller's scope).
You shouldn't do that, what $parent is for you today, tomorrow it can point to anything else (because you could add a new scope in between without knowing it so $parent will then point to the ion-content.
So instead of doing that, you need to use objects and no primitives, for example:
ng-model="form.search_contact"
Thank to that, it will look for the form object through the prototype chain until it finds it on the controller's scope and use it (just what you need).
Read this which is hundred times better than my explanation.

Angularjs List/Detail Edit

I am writing a small AngularJS/Ionic/Cordova application where I have a list of contacts. When the user taps on a contact, I navigate to a new page where details about the contact are shown (first name, last name, phone number). Here, the user can update details about the contact, or delete the contact. The problem I have is when the user deletes the contact the list still shows the deleted item after navigating back.
Right now I am storing the list of contacts in localStorage, but I do plan on eventually persisting these values in SQLite and/or a web service.
I am using two controllers, two html templates, and a factory. Why is the first list not updating when I make changes to a detail item? I am very new to AngularJS so please bear with me.
List Controller
angular
.module('app')
.controller('contactListCtrl', ['$scope', 'Contacts',
function($scope, Contacts) {
$scope.contacts = Contacts.get();
}
])
List Template
<ion-content scroll="false" class="padding-horizontal" has-header="true">
<div class="row padding-vertical">
<div class="col col-center text-center">
<span class="small-text primary-text-color">Contact List</span>
</div>
</div>
<div class="row" >
<div class="col col-center">
<ul class="list">
<li class="item" ng-repeat="contact in contacts" ui-sref="contactListEdit({id: $index})">
{{contact.fName}} {{contact.lName}}
</li>
</ul>
</div>
</div>
</ion-content>
Detail Controller
angular
.module('app')
.controller('editContactCtrl', ['$scope', '$stateParams', 'Contacts',
function($scope, $stateParams, Contacts) {
var contactId = false;
if ($stateParams.id !== 'undefined') {
contactId = $stateParams.id;
}
$scope.contact = Contacts.get(contactId);
$scope.contactId = contactId;
$scope.delete = function(index) {
Contacts.removeContact(index);
window.history.back();
};
}
])
Detail Template
<ion-content scroll="false" class="padding-horizontal" has-header="true">
<div class="row padding-vertical">
<div class="col col-center text-center">
<span class="medium-text primary-text-color">Edit contact</span>
</div>
</div>
<div class="list">
<label class="item item-input">
<input type="text" placeholder="First Name" ng-model="contact.fName">
</label>
<label class="item item-input">
<input type="text" placeholder="Last Name" ng-model="contact.lName">
</label>
<label class="item item-input">
<input type="text" placeholder="Phone" ng-model="contact.mobile">
</label>
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="contact.email">
</label>
<button ng-click="save()" class="button button-full button-positive">
Save
</button>
<button ng-click="delete(contactId)" class="button button-full button-assertive">
Delete
</button>
</div>
</ion-content>
Contacts Factory
angular
.module('app')
.factory('Contacts', ['$http',
function($http) {
return {
get: function(index) {
var contacts;
try {
contacts = JSON.parse(window.localStorage.getItem("contacts"));
if (index >= 0) {
return contacts[index];
}
return contacts;
} catch (e) {
console.log("error parsing json contacts");
return false;
}
},
removeContact: function (index) {
var contactList = this.get();
if (index !== -1) {
contactList.splice(index, 1);
}
console.log(contactList);
this.saveContacts(contactList);
},
setDefaultContacts: function() {
var self = this;
return $http.get('./mock_data/contacts.json').then(function(response) {
// contacts already exist, don't set.
if (window.localStorage.getItem("contacts")) {
return false;
} else {
self.saveContacts(response.data);
return true;
}
});
},
saveContacts: function(contactList) {
window.localStorage.setItem("contacts", JSON.stringify(contactList));
},
};
}
])
I think you will find that the contactListCtrl is not being setup again when you navigate back to it (after a delete). I believe this is because Ionic caches views for you.
What you need to do is listen to $ionicView.beforeEnter event and load your contacts list into your ContactListCtrl scope whenever you receive this event.
So.. Try adding something like this to your controller:
$scope.$on('$ionicView.beforeEnter', function() {
$scope.contacts = Contacts.get();
}
);
Check out: http://ionicframework.com/blog/navigating-the-changes/

Resources