i have problem with my IONIC app.
I want reload my data what i recieve from nodeJS by $http.get, after $http.post.
Here is my code:
.controller('todoTodayCtrl',
function($scope, AuthService, API_ENDPOINT, $http, $state, $ionicPopup) {
$http.get(API_ENDPOINT.url + '/today').then(function(result) {
$scope.todaylist = result.data.msg;
});
})
.controller('todoTodayNewCtrl',
function($scope, AuthService, API_ENDPOINT, $http, $state, $ionicPopup){
$scope.today = {
title: ''
};
$scope.todoNewButton = function() {
$http.post(API_ENDPOINT.url + '/today', $scope.today).then(function(result) {
$state.go('menu.todoToday');
}, function(errMsg) {
var alertPopup = $ionicPopup.alert({
title: 'Nelze přidat Todo',
template: errMsg
});
});
};
})
and first page
<ion-view title="Todo Today" ng-controller="todoTodayCtrl">
<ion-content overflow-scroll="true" padding="true" class="has-header">
<ion-list>
<ion-item class="item-divider" ng-repeat="today in todaylist">{{today.title}} - {{today.time}}</ion-item>
<button class="button button-stable button-block " ui-sref="menu.todoTodayNew">Přidat todo</button>
</ion-list>
</ion-content>
and page with form
<ion-view title="Nové todo today">
<ion-content overflow-scroll="true" padding="true" class="has-header">
<ion-list>
<label class="item item-input">
<span class="input-label">Nový úkol</span>
<input type="text" placeholder="Nová položka" ng-model="today.title">
</label>
<button class="button button-stable button-block " ng-click="todoNewButton()">Přidat todo today</button>
</ion-list>
</ion-content>
You have to push the new today value in your $scope.todaylist in your POST request callback:
$http.post(API_ENDPOINT.url + '/today', $scope.today).then(function(result) {
$scope.todaylist.push(result);
$state.go('menu.todoToday');
}, function(errMsg) {
var alertPopup = $ionicPopup.alert({
title: 'Nelze přidat Todo',
template: errMsg
});
});
Or pass the result to your todoTodayCtl via $state.
$state.go('menu.todoToday', {myParam: {some: 'thing'}})
$stateProvider.state('menu.todoToday', {
url: '/myState',
params: {myParam: null}, ...
and then access the parameter in your controller.
$stateParams.myParam //should be {some: 'thing'}
And my server NodeJs
apiRoutes.post('/today', passport.authenticate('jwt', {session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
console.log(req.body.title);
var newToday = new Today({
title: req.body.title,
time: 'Timeee',
user: user.name
});
newToday.save(function(err) {
if (err) {
res.json({succes: false, msg: 'Error'});
} else {
res.status(200).json({succes: true, msg: newToday});
}
});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
Solved
.controller('todoTodayCtrl', function($scope, $rootScope, AuthService, API_ENDPOINT, $http, $state, $ionicPopup) {
$rootScope.todaylist = [];
$http.get(API_ENDPOINT.url + '/today').then(function(result) {
$rootScope.todaylist = result.data.msg;
});
})
.controller('todoTodayNewCtrl', function($scope, $rootScope, AuthService, API_ENDPOINT, $http, $state, $ionicPopup){
$scope.today = {
title: '',
time: ''
};
$scope.todoNewButton = function() {
$http.post(API_ENDPOINT.url + '/today', $scope.today).then(function(result) {
$rootScope.todaylist.push(result.data.msg);
$state.go('menu.todoToday');
}, function(errMsg) {
var alertPopup = $ionicPopup.alert({
title: 'Nelze přidat Todo',
template: errMsg
});
});
};
})
Related
Right now I am building an ionic app to get user location and launch
them to a particular place an event we be held- But first, I save the
user latitude and longitude to firebase and then when the user click
Launch Navigation the launchNavigator() method we be launch.
but the issue is that the latitude and longitude is returning
undefined
Here is my code:
app.controller('HomeCtrl', function($timeout, $scope, $state, $ionicPopup, $localStorage, $firebaseAuth, $firebaseArray, $firebaseObject, PresenceService,
$ionicLoading, HomeService, $cordovaGeolocation, $cordovaLaunchNavigator){
$scope.Data ={
lat : '',
long: ''
};
$scope.Get =HomeService;
$scope.hasMore = function(){
$scope.check =ListAllUserService.hasMore;
return $scope.check;
};
$scope.LoadAllUser =function(){
$ionicLoading.show({template:'Loading...'});
$scope.Get.load().then(function(data){
$scope.data =data;
console.log($scope.data);
$ionicLoading.hide();
var posOptions = {timeout: 40000, enableHighAccuracy: false};
$cordovaGeolocation.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + ' ' + long);
$scope.Data.lat =lat;
$scope.Data.long =long;
var dataToDb = {latitude: lat, longitude: long, timestamp: new Date().getTime()};
var InsertChatRef = new Firebase('https://bigzill.firebaseio.com');
var insertObj =InsertChatRef.child('GeoLocation').child($scope.data.username);
insertObj.push(dataToDb);
}, function(err) {
console.log(err)
});
});
}
$scope.LoadAllUser();
$scope.launch = function(){
$ionicPopup.alert({
title : "GPS navigation"+ $localStorage.lat,
template: "Navigation Launch"+ $localStorage.long
});
}
$scope.launchNavigator = function() {
$ionicPopup.alert({
title : "GPS Just Launch"+ $scope.Data.lat,
template: "Navigation Launch"+ $scope.Data.long
});
var lat =$scope.Data.lat;
var long =$scope.Data.long;
console.log(lat + ' ' + long);
var destination = [lat, long];
var start = "Benin City, Oka Market";
$cordovaLaunchNavigator.navigate(destination, start).then(function() {
console.log("Navigator launched");
$ionicPopup.alert({
title : "GPS navigation",
template: "Navigation Launch"
});
}, function (err) {
console.error(err);
console.log(lat + ' ' + long);
$ionicPopup.alert({
title : "GPS fail "+ lat,
template: "Navigation Launch "+ long
});
});
};
});
Here is my Html
<ion-view view-title="Home Page">
<ion-content class="has-tabs" style="">
<div class="list card">
<div class="item item-avatar">
<img ng-src="{{data.image_name}}">
<h2>{{data.username}}</h2>
<p>November 05, 1955</p>
</div>
<div class="item item-body">
<img class="full-image" ng-src="{{data.image_name}}">
<p>
This is a "Facebook" styled Card. The header is created from a Thumbnail List item,
the content is from a card-body consisting of an image and paragraph text. The footer
consists of tabs, icons aligned left, within the card-footer.
</p>
<p>
1 Like
5 Comments
{{Data.lat}} ' lat'
{{Data.long}} ' long'
<div ng-click="launchNavigator()">Launch Navigation</div>
</p>
</div>
</div>
</ion-content>
</ion-view>
First, here's the code
controller.js
.controller('FavoritesController', ['$scope', 'dishes', 'favorites', 'favoriteFactory', 'baseURL', '$ionicListDelegate', '$ionicPopup', '$ionicLoading', '$timeout', '$localStorage', function ($scope, dishes, favorites, favoriteFactory, baseURL, $ionicListDelegate, $ionicPopup, $ionicLoading, $timeout, $localStorage) {
$scope.baseURL = baseURL;
$scope.shouldShowDelete = false;
$scope.favorites = favorites;
$scope.dishes = dishes;
console.log($scope.dishes, $scope.favorites);
$scope.toggleDelete = function () {
$scope.shouldShowDelete = !$scope.shouldShowDelete;
console.log($scope.shouldShowDelete);
}
$scope.deleteFavorite = function (index) {
var confirmPopup = $ionicPopup.confirm({
title: 'Confirm Delete',
template: 'Are you sure you want to delete this item?'
});
confirmPopup.then(function (res) {
if (res) {
console.log('Ok to delete');
favoriteFactory.deleteFromFavorites(index);
var old_favorite = JSON.parse($localStorage.get('favorites'));
var leng = Object.keys(old_favorite).length;
for (var i = 0; i < leng; i++) {
if (Object.keys(old_favorite)[i] == index) {
console.log("Deleted from localstorage! " + Object.keys(old_favorite)[i]);
old_favorite.splice(old_favorite.indexOf(index), 1);
$localStorage.storeObject('favorites', old_favorite);
}
}
} else {
console.log('Canceled delete');
}
});
$scope.shouldShowDelete = false;
}
}])
services.js
.factory('favoriteFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
var favFac = {};
var favorites = [];
favFac.addToFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
favorites.push({id: index});
};
favFac.deleteFromFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
favorites.splice(i, 1);
console.log("Deleted !" + index);
}
}
}
favFac.getFavorites = function () {
return favorites;
};
return favFac;
}])
favorites.html
<ion-view view-title="My Favorites">
<ion-nav-buttons side="secondary">
<div class="buttons">
<button class="button button-icon icon ion-ios-minus-outline"
ng-click="toggleDelete()"></button>
</div>
</ion-nav-buttons>
<ion-content>
<ion-list show-delete="shouldShowDelete">
<ion-item ng-repeat="dish in dishes | favoriteFilter:favorites" href="#/app/menu/{{dish.id}}" class="item-thumbnail-left" on-swipe-left="deleteFavorite(dish.id)">
<img ng-src="{{baseURL+dish.image}}" on-swipe-left="deleteFavorite(dish.id)">
<h2>{{dish.name}}
<span style="font-size:75%">{{dish.price | currency}}</span>
<span class="badge badge-assertive">{{dish.label}}</span></h2>
<p>{{dish.description}}</p>
<ion-delete-button class="ion-minus-circled"
ng-click="deleteFavorite(dish.id)">
</ion-delete-button>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
app.js
.state('app.favorites', {
url: '/favorites',
views: {
'mainContent': {
templateUrl: 'templates/favorites.html',
controller:'FavoritesController',
resolve: {
dishes: ['menuFactory', function(menuFactory){
return menuFactory.query();
}],
favorites: ['favoriteFactory', function(favoriteFactory) {
return favoriteFactory.getFavorites();
}]
}
}
}
})
So, after I attempt to use the deleteFavorite Function from the controller.js and the index inside the localstorage was success deleted, the data on the favorites.html couldn't updated, it couldn't deleted from the favorties.html immediately.
I need to refresh my browser first to show the up-to-date list based on the localstorage.
I hope that I can show the up-to-date data based on the localstorage data without refresh the page.
Did I make something wrong on here?
Thank you in advance!
I want to display ng-model value from page to input in another page
I Want display selected issue from issues page to contact page
Issue Controller
.controller('IssueCtrl', function($scope, $http) {
$http.get('api/issues').then(function(resp) {
console.log('Success', resp);
$scope.issues = resp.data;
}, function(err) {
console.error('ERR', err);
$scope.issues = err;
});
})
Contact Controller
.factory('Post', function($resource) {
return $resource('api/add_new_order',{problem: "#problem"});
})
.controller('ContactCtrl', function($scope, Post) {
// Get all posts
$scope.posts = Post.query();
// Our form data for creating a new post with ng-model
$scope.postData = {};
$scope.newPost = function() {
var post = new Post($scope.postData);
post.$save();
}
$scope.issues = {};
$scope.answer = function(){
console.log($scope.issues.name);
}
})
Issue View
<ion-list ng-repeat="item in issues">
<ion-radio ng-model="issues.name" ng-value="'{{item.issue}}'">
{{item.issue}}
</ion-radio>
</ion-list>
Contact View
<form ng-submit="newPost()">
<label class="item item-input">
<span class="input-label">Problem :</span>
<input type="text" name="problem" ng-model="postData.problem">
</label>
</form>
Your API requests should be on independent services, so they can be accessed by any controller.
As you seen to know how a factory works, I will give you an example.
.factory('IssuesService', function($http) {
var issues = [];
return {
all: function() {
return $http.get('api/issues')
.then(function(data){ // Optional callback inside service
issues = data;
});
}
}
})
.controller('ContactCtrl', function($scope, Post, IssuesService) {
...
$scope.issues = [];
IssuesService.all().then(function(data){
$scope.issues = data;
})
...
})
.controller('IssueCtrl', function($scope, $http) {
IssuesService.all()
.then(function(resp) {
console.log('Success', resp);
$scope.issues = resp.data;
}, function(err) {
console.error('ERR', err);
$scope.issues = err;
});
})
I've been following the Thinkster Mean Stack tutorial, and it works wonderfully. So I have created my own project, and so far everything works fine.
However, they didn't cover how to delete posts.
And I can for the life for me not figure out how to delete an element from the data.
AngularApp.js
var app = angular.module('KOL', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: "/views/home.ejs",
controller: 'kolCtrl',
resolve: {
patientPromise: ['patients', function(patients) {
return patients.getAll();
}]
}
})
.state('details', {
url: '/details/{id}',
templateUrl: './views/details.html',
controller: 'detailsCtrl'
});
$urlRouterProvider.otherwise('home');
}])
.factory('patients', ['$http', function($http){
var object = {
patients: []
};
object.getAll = function() {
return $http.get('/patients').success(function(data) {
angular.copy(data, object.patients);
});
}
object.create = function(patient) {
return $http.post('/patients', patient).success(function(data){
object.patients.push(data);
});
}
};
return object;
}])
.controller('kolCtrl', ['$scope', 'patients',
function($scope, patients){
$scope.patients = patients.patients;
$scope.selectedItem = $scope.patients[0];
$scope.addPost = function() {
if(!$scope.title || $scope.title === '') { return; }
if(!$scope.age || $scope.age === '') { return; }
patients.create({
name: $scope.title,
age: $scope.age,
})
$scope.title = '';
$scope.age = '';
};
object.delete = function(patient)
}])
.controller('detailsCtrl', [
'$scope',
'$stateParams',
'patients',
function($scope, $stateParams, patients){
$scope.patient = patients.patients[$stateParams.id];
}])
;
Home.ejs
<div class="container">
<div clas="row">
<div style="width: 200px; margin-top: 100px">
<select ng-model="selectedItem" ng-options="patients.name for patients in patients" class="pull-left form-control" name="Vælg"></select>
</div>
<div class="viewbox pull-right">
<h3>Patient: {{selectedItem.name}}</h3>
<p>Age: {{selectedItem.age}} </p>
<p>index: {{patients.indexOf(selectedItem)}}</p>
<button>Rediger</button>
<button ng-click="deleteItem(patients.indexOf(selectedItem))">Delete</button>
</div>
</div>
<div class="row" class="pull-left">
<div style="width: 200px; margin-top: 100px">
<form role="form" class="form-group" ng-submit="addPost()">
<input class="form-control" type="text" ng-model="title" />
<input class="form-control" type="text" ng-model="age" />
<button type="submit">Add</button>
</form>
</form>
</div>
</div>
</div>
index.js (route get and post)
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var mongoose = require('mongoose');
var Patient = mongoose.model('Patient');
router.get('/patients', function(req, res, next) {
Patient.find(function(err, patients){
if(err){ return next(err); }
res.json(patients);
});
});
router.post('/patients', function(req, res, next) {
var patient = new Patient(req.body);
patient.save(function(err, post){
if(err){ return next(err); }
res.json(patient);
});
});
router.delete('/patients/:patient', function(req, res, next) {
req.patient.remove(function(err, patient){
if (err) { return next(err); }
res.json(patient);
});
});
router.param('patient', function(req, res, next, id) {
var query = Patient.findById(id);
query.exec(function (err, patient){
if (err) { return next(err); }
if (!post) { return next(new Error('can\'t find patient')); }
req.patient = patient;
return next();
});
});
router.get('/details/:patient', function(req, res) {
res.json(req.patient);
});
module.exports = router;
I suspect the answer is quite straightforward, given the other code, but maybe not?
Thanks.
According to your function that you are passing to the router.delete in your index.js file:
router.delete('/patients/:patient', function(req, res, next) {
req.patient.remove(function(err, patient){
if (err) { return next(err); }
res.json(patient);
});
});
You'll have to append the patients.id to the url when using the delete verb with the $http service. So you can add a delete method to the object in your patients factory:
.factory('patients', ['$http', function($http){
var object = {
patients: []
};
object.getAll = function() {
return $http.get('/patients').success(function(data) {
angular.copy(data, object.patients);
});
}
object.create = function(patient) {
return $http.post('/patients', patient).success(function(data){
object.patients.push(data);
});
}
//add patient id to the url
object.delete = function(patient) {
return $http.delete('/patients/',patient).success(function(data){
console.log(data);
});
}
}
};
return object;
}])
object.delete = function(patient) {
return $http.delete('/patients', patient).success(function(data){
for(var i = 0; i < object.patients.length; i++) {
if(object.patients[i].id == patient.id) {
object.patients.splice(i, 1);
}
});
Something like that maybe, hard to say without knowing the response. If the response (data) is the deleted patient then you can use "if(object.patients[i].id == data.id)" instead
I am currently having an issue where when I try to create a new setting my view is not being updated until I refresh the page. Can anyone point me into the right direction? If I am going about this the wrong way please let me know a better way to do this.
app.factory('SettingsFactory', function ($http, $q) {
//$scope.settingData = {}
return {
getAllOptionsAsync: function(callback) {
var deferred = $q.defer();
$http.get('/api/settings').success(callback);
},
deleteOptionAsync: function(id) {
//console.log('reached');
var deferred = $q.defer();
$http.delete('/api/settings/' + id);
},
createOptionAsync: function(settingData) {
var deferred = $q.defer();
$http.post('/api/settings', settingData).success(function(data) { console.log(data);
deferred.resolve(data);
// console.log(deferred.promise);
return deferred.promise;
});
}
};
});
var controllers = {};
controllers.SettingsController = function($scope, SettingsFactory) {
//$scope.settings = SettingService.list();
SettingsFactory.getAllOptionsAsync(function(results) {
//console.log(results);
$scope.settings = results;
});
$scope.create = function() {
// console.log('called');
// console.log($scope.formData);
SettingsFactory.createOptionAsync($scope.formData).then(function(data) {
console.log(data);
$scope.settings = data;
});
}
$scope.delete = function(id) {
//console.log(id.entity._id);
SettingsFactory.deleteOptionAsync(id.entity._id);
}
$scope.gridOptions = {
data: 'settings',
multiSelect: false,
columnDefs: [
{field: 'option'},
{field: 'value'},
{displayName: 'Edit', cellTemplate: '<button id="editBtn" type="button" class="btn btn-primary" ng-click="open(settings._id)" >Edit</button> <button id="deleteBtn" type="button" class="btn btn-primary" ng-click="delete(row)" >Edit</button> '}
]
};
}
Inside of the then or anytime you are updating the scope in a callback you need to wrap the $scope.settings=data with a scope.apply.
$scope.$apply(function() {
$scope.settings=data;
});
Typed out on phone so there might be an error.