How to use Cordova Geolocation with OpenWeatherMap in Ionic? - angularjs

I have an Ionic project connected to the OpenWeatherMap API, and I would like to use the Cordova plugin for geolocation; I tried to connect them, and I managed to be geolocalized, but impossible to get an answer from the API ...
However the API was configured correctly since I was able to get data before putting the plugin ...
Here is the code :
controllers.js =>
angular.module('weather')
.controller('WeatherCtrl', function($scope, $cordovaGeolocation, $http, OpenWeatherConfig) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}, function(err) {
});
$scope.state = false;
$scope.weatherData = {
icon: '',
main: '',
city: '',
description: '',
coord: '',
temp: ''
};
$scope.loadWeather = function(lat, lng) {
var url = OpenWeatherConfig.searchUrl + 'lat=' + lat + '&lon=' + lng + OpenWeatherConfig.units + OpenWeatherConfig.appid;
$http.get(url).success(function(data) {
$scope.weatherData.icon = OpenWeatherConfig.imgUrl + data.weather[0].icon + '.png';
$scope.weatherData.main = data.weather[0].main;
$scope.weatherData.city = data.name;
$scope.weatherData.description = data.weather[0].description;
$scope.weatherData.coord = data.coord;
$scope.weatherData.temp = data.main.temp;
$scope.state = true;
});
};
});
weather.html =>
<ion-view>
<ion-content overflow-scroll="false" class="weather-home">
<button class="button button-full button-calm" ng-click="loadWeather()">
Search
</button>
<div ng-if="state" class="forecast">
<img src="{{weatherData.icon}}" class="icon"/>
<label class="bigText">{{weatherData.main}}</label>
<div class="mainText">Town : {{weatherData.city}}</div>
<div class="mainText">Current conditions : {{weatherData.description}}</div>
<div class="mainText">Geographical coordinates : {{weatherData.coord}}</div>
<div class="bigText">{{weatherData.temp}} °C</div>
</div>
</ion-content>
</ion-view>
Nothing appears in the Firefox console, and I have only made changes in these files since the API was running ...

Thanks to "digit" to helping me find the way !
Here is the solution :
controllers.js =>
.controller('WeatherCtrl', function($scope, $cordovaGeolocation, $http, OpenWeatherConfig) {
$scope.state = false;
$scope.weatherData = {
icon: '',
main: '',
city: '',
description: '',
lat:'',
lon: '',
temp: ''
};
$scope.loadWeather = function() {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var url = OpenWeatherConfig.searchUrl + 'lat=' + lat + '&lon=' + lon + OpenWeatherConfig.units + OpenWeatherConfig.appid;
$http.get(url).success(function(data) {
$scope.weatherData.icon = OpenWeatherConfig.imgUrl + data.weather[0].icon + '.png';
$scope.weatherData.main = data.weather[0].main;
$scope.weatherData.city = data.name;
$scope.weatherData.description = data.weather[0].description;
$scope.weatherData.lat = data.coord.lat;
$scope.weatherData.lon = data.coord.lon;
$scope.weatherData.temp = data.main.temp;
$scope.state = true;
});
}, function(err) {
});
};
});
weather.html =>
<ion-view>
<ion-content overflow-scroll="false" class="weather-home">
<button class="button button-full button-calm" ng-click="loadWeather()">
Search
</button>
<div ng-if="state" class="forecast">
<img src="{{weatherData.icon}}" class="icon"/>
<label class="bigText">{{weatherData.main}}</label>
<div class="mainText">Town : {{weatherData.city}}</div>
<div class="mainText">Current Conditions : {{weatherData.description}}</div>
<div class="mainText">Geographical coordinates : {{weatherData.lat}}, {{weatherData.lon}}</div>
<div class="bigText">{{weatherData.temp}} °C</div>
</div>
</ion-content>
</ion-view>

Related

How to access multiple services in angularjs controller

In an aspnetboilerplate .cshtml page, we have
div ng-controller="app.views.automate as vm"
, this angular controller access the automateService from asp.net mvc controller.
inside that div , we are loading partial view from another .cshtml file, here it should have a different service(excelService) from the Asp.net mvc controller. How to achieve it.
Angular.js
(function () {
var controllerId = 'app.views.automate';
angular.module('app').controller(controllerId, [
'$scope', 'abp.services.app.automate', function ($scope, automateService) {
var vm = this;
//Automate logic...
//Model
vm.currentStep = 1;
vm.steps = [
{
step: 1,
name: "First step",
template: "/App/Main/views/automate/step1.cshtml",
controller: 'app.views.excel as vm'
},
{
step: 2,
name: "Second step",
template: "/App/Main/views/automate/step2.cshtml"
},
{
step: 3,
name: "Third step",
template: "/App/Main/views/automate/step3.cshtml",
controller: 'app.views.capacity as vm'
}
];
//Functions
vm.gotoStep = function (newStep) {
vm.currentStep = newStep;
//$scope.ParseExcel();
}
vm.getStepTemplate = function () {
for (var i = 0; i < vm.steps.length; i++) {
if (vm.currentStep == vm.steps[i].step) {
return vm.steps[i].template;
}
}
}
vm.save = function () {
//todo: save data...
//vm.location['abq'].center
//alert(vm.location.abq.center);
// vm.enterCapacity(vm.location);
}
vm.enterCapacity = function () {
// alert(vm.capacity.locations[0].center);
automateService.calculateCapacity(vm.capacity).then(function () {
abp.notify.info(app.localize('SavedSuccessfully'));
});
}
$scope.SelectedFileForUpload = null; //initially make it null
$scope.BindData = null;
$scope.showLoader = false;
$scope.IsVisible = false;
$scope.UploadFiles = function (files) {
$scope.$apply(function () {
$scope.Message = '';
$scope.SelectedFileForUpload = files[0];
});
}
vm.capacity = {
locations: [
{ city: "abq", center: 0, housing: 0 },
{ city: "han", center: 0, housing: 0 },
{ city: "udh", center: 0, housing: 0 },
{ city: "dhn", center: 0, housing: 0 },
{ city: "spp", center: 0, housing: 0 },
{ city: "rt", center: 0, housing: 0 },
{ city: "has", center: 0, housing: 0 },
{ city: "jed", center: 0, housing: 0 },
{ city: "ry", center: 0, housing: 0 },
{ city: "yan", center: 0, housing: 0 },
{ city: "tan", center: 0, housing: 0 },
{ city: "itq", center: 0, housing: 0 },
{ city: "abq", center: 0, housing: 0 }
]
};
}
]);
})();
Angular.html
<div class="row clearfix" ng-controller="app.views.automate as vm">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="header">
<h2>
Automate
</h2>
</div>
<div class="body">
<div id="wizard-step-container">
<ul class="nav nav-pills nav-justified">
<li ng-repeat="step in vm.steps" ng-class="{'active':step.step == vm.currentStep}"><a ng-click="vm.gotoStep(step.step)" href="">{{step.step}}. {{step.name}}</a></li>
</ul>
</div>
<div id="wizard-content-container">
<ng-include src="vm.getStepTemplate()"></ng-include>
</div>
<div id="wizard-navigation-container">
<div class="pull-right">
<span class="btn-group">
<button ng-disabled="vm.currentStep <= 1" class="btn btn-default" name="previous" type="button" ng-click="vm.gotoStep(vm.currentStep - 1)"><i class="fa fa-arrow-left"></i> Previous step</button>
<button ng-disabled="vm.currentStep >= vm.steps.length" class="btn btn-primary" name="next" type="button" ng-click="vm.gotoStep(vm.currentStep + 1)">Next step <i class="fa fa-arrow-right"></i></button>
</span>
<button ng-disabled="vm.currentStep != vm.steps.length" class="btn btn-success" name="next" type="button" ng-click="vm.save()"> <i class="fa fa-floppy-o"></i> Save</button>
</div>
</div>
</div>
</div>
</div>
</div>
Step1.html
<div class="step1">
<div class="loading-icon" id="loading" ng-show="showLoader">
</div>
<div class="form-inline">
<input type="file" class="form-control" name="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onchange="angular.element(this).scope().UploadFiles(this.files)" />
<input type="button" value="Preview" class="btn btn-primary" ng-disabled="!SelectedFileForUpload" ng-click="ParseExcel()" />
<input type="button" value="Insert" style="margin-left: 15px;" class="btn btn-success" ng-show="IsVisible" ng-click="InsertData()" />
</div>
<br />
</div>
Excel.js
(function () {
angular.module('app').controller('app.views.excel', [
'$scope', 'abp.services.app.excel',
function ($scope, ExcelService) {
var vm = this;
$scope.ParseExcel = function () {
var formData = new FormData();
var file = $scope.SelectedFileForUpload;
formData.append('file', file);
$scope.showLoader = true; //show spinner
var response = Excelservice.SendExcelData(formData); //calling service
response.then(function (d) {
var res = d.data;
$scope.BindData = res;
$scope.IsVisible = true; //showing the table after databinding
$scope.showLoader = false; //after success hide spinner
}, function (err) {
console.log(err.data);
console.log("error in parse excel");
});
}
$scope.InsertData = function () {
var response = Excelservice.InsertToDB();
response.then(function (d) {
var res = d.data;
if (res.toString().length > 0) {
$scope.Message = res + " Records Inserted";
$scope.IsVisible = false; //used to disable the insert button and table after submitting data
angular.forEach(
angular.element("input[type='file']"),
function (inputElem) {
angular.element(inputElem).val(null); //used to clear the file upload after submitting data
});
$scope.SelectedFileForUpload = null; //used to disable the preview button after inserting data
}
}, function (err) {
console.log(err.data);
console.log("error in insertdata");
});
}
}
]);
angular.module('app').service("Excelservice", function ($http) {
this.SendExcelData = function (data) {
var request = $http({
method: "post",
withCredentials: true,
url: '/Home/ReadExcel',
data: data,
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity
});
return request;
}
this.InsertToDB = function () {
var request = $http({
method: "get",
url: '/Home/InsertExcelData',
data: {},
datatype: 'json'
});
return request;
}
});
//used to check the extension of file while uploading
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls");
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
}
else return true;
}
})();
Error Details
(function () {
var controllerId = 'app.views.automate';
angular.module('app').controller(controllerId, [
'$scope','Excelservice', 'abp.services.app.automate', function ($scope, Excelservice, automateService) {
var vm = this;
// ...
}]);
})();
https://github.com/aspnetboilerplate/aspnetboilerplate/issues/3789#issuecomment-416031257

latitude and longitude in $cordovaGeolocation returning undefined

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>

Reload controller with $http.get after $http.post

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
});
});
};
})

Display google map directions when page load

At the moment i have an ionic app, and with angular i created a map that give directions from current user location to a predefined address, if user press "get directions". I will like to display the directions when page load without having to press that button.
This is the controller:
.controller('ContactCtrl', function ($scope, $ionicPlatform, uiGmapGoogleMapApi, $ionicPopup, $cordovaGeolocation) {
// uiGmapGoogleMapApi is a promise.
// The "then" callback function provides the google.maps object.
uiGmapGoogleMapApi.then(function (maps) {
var myLatlng = new google.maps.LatLng(51.51139, -0.2237284);
var mapOptions = {
center: myLatlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// directions object -- with defaults
$scope.directions = {
origin: "",
destination: "12 High Street Kensington",
showList: false
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// instantiate google map objects for directions
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$ionicPlatform.ready(function () {
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (pos) {
map.setCenter((51.498265, -0.313515));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map
});
geocoder.geocode({
latLng: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)
}, function (responses) {
if (responses && responses.length > 0) {
$scope.directions.origin = responses[0].formatted_address;
} else {
var alertPopup = $ionicPopup.alert({
title: 'Cannot determine address at this location!',
template: 'Please try again!'
});
alertPopup.then(function (res) {
console.log('Cannot determine address at this location!');
});
}
});
}, function (err) {
$ionicPopup.alert({
title: 'Unable to find your location!',
template: 'Please try again!'
});
});
});
$scope.map = map;
// get directions using google maps api
$scope.getDirections = function () {
var request = {
origin: $scope.directions.origin,
destination: $scope.directions.destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap($scope.map);
directionsDisplay.setPanel(document.getElementById('directionsList'));
$scope.directions.showList = true;
} else {
var alertPopup = $ionicPopup.alert({
title: 'Cannot find address at this location!',
template: 'Please try again!'
});
alertPopup.then(function (res) {
console.log('Google route unsuccesful! Please try again!');
});
}
});
}
});
})
<div class="panel-body">
<div id='map' data-tap-disabled="true">
</div>
<div class="list">
<label class="item item-input item-stacked-label">
<span class="input-label">Origin Address (A)</span>
<input type="text" id="origin" placeholder="Origin address" ng-model="directions.origin"/>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Destination Address (B)</span>
<input type="text" id="destination" placeholder="Destination address" ng-model="directions.destination"/>
</label>
</div>
<div class="pad10">
<button class="button button-block button-assertive" ng-click="getDirections()">Get Directions</button>
</div>
<div id="directionsList" ng-show="directions.showList" class="pad10"></div>
</div>
UPDATE
When i try your code i get the following message in console:
getCurrentPosition() and watchPosition() are deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.
ionic.bundle.js:20306 TypeError: map.setCenter is not a function
at $cordovaGeolocation.getCurrentPosition.then.$ionicPopup.alert.title (controllers.js:306)
at processQueue (ionic.bundle.js:21888)
at ionic.bundle.js:21904
at Scope.$eval (ionic.bundle.js:23100)
at Scope.$digest (ionic.bundle.js:22916)
at ionic.bundle.js:23139
at completeOutstandingRequest (ionic.bundle.js:13604)
at ionic.bundle.js:13984(anonymous function) # ionic.bundle.js:20306
services.js:65 user Id = c621662e-7389-4c4f-9677-35c1e126f6be
2controllers.js:356 Google route unsuccesful! Please try again!
maybe call getDirection in your init promise?
.controller('ContactCtrl', function ($scope, $ionicPlatform, uiGmapGoogleMapApi, $ionicPopup, $cordovaGeolocation) {
// uiGmapGoogleMapApi is a promise.
// The "then" callback function provides the google.maps object.
uiGmapGoogleMapApi.then(function (maps) {
var myLatlng = new google.maps.LatLng(51.51139, -0.2237284);
var mapOptions = {
center: myLatlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// directions object -- with defaults
$scope.directions = {
origin: "",
destination: "12 High Street Kensington",
showList: false
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
// instantiate google map objects for directions
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$ionicPlatform.ready(function () {
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (pos) {
$scope.map.setCenter((51.498265, -0.313515));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: $scope.map
});
geocoder.geocode({
latLng: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)
}, function (responses) {
if (responses && responses.length > 0) {
$scope.directions.origin = responses[0].formatted_address;
} else {
var alertPopup = $ionicPopup.alert({
title: 'Cannot determine address at this location!',
template: 'Please try again!'
});
alertPopup.then(function (res) {
console.log('Cannot determine address at this location!');
});
}
});
$scope.getDirections();
}, function (err) {
$ionicPopup.alert({
title: 'Unable to find your location!',
template: 'Please try again!'
});
});
});
// get directions using google maps api
$scope.getDirections = function () {
var request = {
origin: $scope.directions.origin,
destination: $scope.directions.destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap($scope.map);
directionsDisplay.setPanel(document.getElementById('directionsList'));
$scope.directions.showList = true;
} else {
var alertPopup = $ionicPopup.alert({
title: 'Cannot find address at this location!',
template: 'Please try again!'
});
alertPopup.then(function (res) {
console.log('Google route unsuccesful! Please try again!');
});
}
});
}
});
})

update/refresh angularjs ng-repeat with data from server

I try to buil a website to like some pictures.
I can load the picture, but I want to have a like system with who like the picture.
my problem was I have to refresh the page to see who like this picture and increment the count.
this my controller :
$scope.loadingpics = function (){
$http.get('/api/photos')
.success(function(awesomeThings) {
console.log(awesomeThings);
$scope.firstname = awesomeThings;
})
.error(function (err){
$scope.errors.other = err.message;
});
};
$scope.upVote = function(index){
$scope.vote = 1;
var ref = index;
var nom = index.url.substr(30, 40);
var num = index.vote + 1;
$http.put('api/photos/' + nom, {
email: email,
vote: num
})
.success(function (data) {
$scope.firstname = data;
$scope.loadingpics();
})
.error(function (err){
$scope.errors.other = err.message;
});
};
this is my view :
<li ng-repeat="image in firstname | orderBy: 'firstname'" ng-show="isLoggedIn()" class="thumbnail" title="Image 1" on-last-repeat>
<img ng-src="../assets/images/Pouce.png" ng-click="upVote(image)" data-toggle="popover" data-content="And here's some amazing content. It's very engaging. Right?" data-placement="right" title="Popover title">
</li>
this is my schema :
var PhotoSchema = new Schema({
url: String,
firstname: String,
email: [String],
info: String,
vote: Number,
active: Boolean
});
Thanks for your help :D
Instead of storing only the number of likes in your schema, store an array of object :
var PhotoSchema = new Schema({
url: String,
firstname: String,
email: [String],
info: String,
vote: [{
date: Date,
user: String
}],
active: Boolean
});
I just change my upVote function by adding a $scope.watch and $scope apply.
This is my example :
$scope.upVote = function(index){
$scope.vote = 1;
var ref = index;
var nom = index.url.substr(30, 40);
console.log(nom);
console.log(index.vote);
var num = index.vote + 1;
console.log(index);
$http.put('api/photos/' + nom, {
email: email,
})
.success(function (data) {
$scope.firstname = data;
})
.error(function (err){
$scope.errors.other = err.message;
});
$scope.$watch($scope.firstname, $scope.loadingpics());
$scope.apply();
};

Resources