I am creating a service to get the values saved as "FirstName" in a Row "name", when save is ok i have the values in the database, but when i try to get this values i have something like this:
people:
-
All the values in the list empty but i don't know why this happen if it is a problem in the controller or in the service.
<script src="https://www.parsecdn.com/js/parse-1.3.2.min.js"></script>
<div ng-app="app">
<ul ng-controller="MyCtrl">
people
<li ng-repeat="person in people">{{person}}</li>
</ul>
</div>
<script type="text/javascript">
Parse.initialize("key", "key");
var People = Parse.Object.extend("People");
var peoples= new People();
peoples.set("name", "FirstName");
peoples.save(null),{
success:function(peoples){
peoples.save();
}
}
var app = angular.module('app', []);
app.controller("MyCtrl", ["$scope", "PeopleService", function($scope, PeopleService){
$scope.people = PeopleService.getPeople();
}]);
app.service("PeopleService", function($q){
var people = null;
return {
getPeople: function(){
var deferred = $q.defer();
people = [];
var queryObject = new Parse.Query(People);
queryObject.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var result = results[i];
people.push(result.get("name"));
}
deferred.resolve(people);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}
}
});
</script>
You should set the $scope.people value from the success callback function of parse.com call.
Code
app.controller("MyCtrl", ["$scope", "PeopleService", function($scope, PeopleService){
PeopleService.getPeople().then(function(data){ //success fn
$scope.people = data
},function(data){ //error fn
$scope.people = data
});
}]);
Related
I need help to store my chosen image to localStorage but i don't know where to add it on my angularjs script 🙁 what I want is when i already chose a photo that I want, i like to save it on localStorage and will stay after i refresh or close the browser. Please Help! here is my script below...enter image description hereenter image description hereenter image description here
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Photo and store on localStorage using AngularJS 1.X</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js"></script>
<style>
img{width:200px; height:200px;}
</style>enter image description here
</head>
<body>
<div ng-app="plunkr">
<div ng-controller="UploadController">
<form>
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc">
<!-- <input type="file" ng-file-select="onFileSelect($files)" multiple> -->
</form>
<img ng-src="{{imageSrc}}" />
</div>
</div>
<script>
var app = angular.module('plunkr', [])
app.controller('UploadController', function($scope, fileReader) {
$scope.imageSrc = "";
$scope.$on("fileProgress", function(e, progress) {
$scope.progress = progress.loaded / progress.total;
});
});
app.directive("ngFileSelect", function(fileReader, $timeout) {
return {
scope: {
ngModel: '='
},
link: function($scope, el) {
function getFile(file) {
fileReader.readAsDataUrl(file, $scope)
.then(function(result) {
$timeout(function() {
$scope.ngModel = result;
});
});
}
el.bind("change", function(e) {
var file = (e.srcElement || e.target).files[0];
getFile(file);
});
}
};
});
app.factory("fileReader", function($q, $log) {
var onLoad = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.resolve(reader.result);
});
};
};
var onError = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.reject(reader.result);
});
};
};
var onProgress = function(reader, scope) {
return function(event) {
scope.$broadcast("fileProgress", {
total: event.total,
loaded: event.loaded
});
};
};
var getReader = function(deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
reader.onprogress = onProgress(reader, scope);
return reader;
};
var readAsDataURL = function(file, scope) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
});
</script>
</body>
</html>
After loading the selected image, just save the image string to local storage:
function getFile(file) {
fileReader.readAsDataUrl(file, $scope)
.then(function(result) {
localStorage.setItem('myImage', result);
$timeout(function() {
$scope.ngModel = result;
});
});
}
Then you can retreive image from local storage by calling:
imageResult = localStorage.getItem('myImage')
I have a json object that come from node server as a variable "msg" and receive it by socket.on
and I want to use this json with angularjs as ng-repeat
please help !
<script>
var socket = io();
socket.on('chat message', function(msg){
$("ul").html(msg);
var app = angular.module('myApp', []);
app.controller('jsCtrl', function($scope) {
$scope.msgs = msg;
});
});
</script>
<ul>
<li ng-repeat="item in msgs">
{{item.Name}}
</li>
</ul>
i have in server this code var
initData = JSON.parse('<%-JSON.stringify(data)%>');
and I think I must use json.stringify(msg); to convert it to json
how can I use it with angular js ng-repeat !
Maybe,
(function() {
angular.module('myApp', [])
.controller("jsCtrl", jsCtrl);
jsCtrl.$inject = ['$scope'];
function jsCtrl($scope) {
var socket = io();
socket.on('chat message', function(msg) {
$scope.msgs = angular.fromJson(msg);
}
}
});
})();
It's just an idea, I don't know exactly what kind of data is coming.
I'm new with Google Maps and I add ng-map but I have the same problem of official plunker code plunker, markers don't appear.
This is my Angularjs code:
//Google maps
var app = angular.module('myApp',['ngMap', 'ngAnimate', 'ui.bootstrap', 'ui.select']);
app.controller('mapController', ['$scope','$http', 'NgMap', function($scope, $http, NgMap) {
NgMap.getMap().then(function(map) {
//Get all buildings for maps
$http({
method: 'GET',
url: '/booking/building/1',
}).then(function successCallback(response) {
if (typeof response.data.success == 'undefined'){
window.location.href = "/500";
}else if (response.data.success==true){
for (var i=0; i < response.data.result.length;i++){
var latLng = new google.maps.LatLng(response.data.result[i].latitude, response.data.result[i].longitude);
vm.dynMarkers.push(new google.maps.Marker({position:latLng, title:response.data.result[i].name}));
}
}else if (response.data.success==false)
notifyMessage(response.data.result, 'error');
}, function errorCallback(response) {
window.location.href = "/500";
});
vm.markerClusterer = new MarkerClusterer(map, vm.dynMarkers, {});
});
});
In this case I have only 1 city, but in the future I may have a loto of coordinates.
In Html I have this script about ng-map:
<!-- Maps -->
<script th:src="#{/static/assets/plugins/angular-maps/ng-map.min.js}"
type="text/javascript"></script>
<script
src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/testapp/scripts/markerclusterer.js"></script>
<script>
MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_
= 'https://raw.githubusercontent.com/googlemaps/js-marker-clusterer/gh-pages/images/m1.png'; //changed image path
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=key">
</script>
I tryed to remove
<script>MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH = 'https://raw.githubusercontent.com/googlemaps/js-marker-clusterer/gh-pages/images/m1.png'; //changed image path
</script>
but the result still the same. I would like to uso only maps CDN link.
I found out that vm.markerClusterer = new MarkerClusterer(map, vm.dynMarkers, {}); is called before for inside ajax is terminated so the vatiable is empty so I moved it after the end of for and it works
for (var i=0; i < response.data.result.length;i++){
var latLng = new google.maps.LatLng(response.data.result[i].latitude, response.data.result[i].longitude);
vm.dynMarkers.push(new google.maps.Marker({position:latLng, title:response.data.result[i].name}));
}
vm.markerClusterer = new MarkerClusterer(map, vm.dynMarkers, {});
I had been reading up on AngularJS Factory and Services and came across a lot of examples. But I'm not understanding the logic behind them and can't get them to work either.
myApp.service('loginCheck', function(Facebook) {
this.loggedIn = false;
Facebook.login(function(response) {
if (response.status == 'connected') {
this.loggedIn = true;
}
});
});
I need to get this service to return the loggedIn variable, if my idea of the concept is right. Should I use a factory instead? I need to store this variable all along, without making the call again every once I need it. How can I do it. I couldn't really understand the difference between factory and service. I'm a beginner here.
if(loginCheck.loggedIn){
console.log("logged in!");
}
else{
console.log("not logged in :/")
}
Thank you.
You can do this,
app.service('MyUser', [function($scope) {
this.loggedIn = false;
return {
getStatus: function() {
//call fb api
this.loggedIn = true;
return this.loggedIn;
}
}
}]);
DEMO
var app = angular.module('app', []);
app.controller('loginController',['$scope', 'MyUser',function($scope, MyUser)
{
$scope.isloggedin = MyUser.getStatus();
alert($scope.isloggedin);
}]);
app.service('MyUser', [function($scope) {
this.loggedIn = false;
return {
getStatus: function() {
this.loggedIn = true;
return this.loggedIn;
}
}
}]);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body ng-app="app" ng-controller="loginController">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js"></script>
</body>
</html>
Define a factory and passed to your controller as dependency.
var myApp = angular.module('myApp', []);
myApp.factory('loginCheck', ["Facebook", function(Facebook) {
var object = {
loggedIn: false,
loginFacebook: function() {
// do facebook login here:
//Facebook.login(function(response) {
// if (response.status == 'connected') {
object.loggedIn = true;
// };
}
};
object.loginFacebook();
return object;
}]);
myApp.controller('myCtrl', ['loginCheck', '$scope', function(loginCheck, $scope) {
$scope.loggedIn = loginCheck.loggedIn;
}]);
check this jsFiddle sample here.
I don't know about facebook authentication, but I think these links may help you : https://blog.brunoscopelliti.com/facebook-authentication-in-your-angularjs-web-app/ , https://developers.facebook.com/docs/javascript/howto/angularjs
To find different between service and factory look at this question or this link.
This is my html
<!DOCTYPE html>
<html x-ng-app="demo">
<head>
<title>Demo</title>
<script src="../demo/js/angular.js"></script>
<script src="../demo/js/jquery-3.1.0.js"></script>
<script src="../demo/js/jquery-3.1.0.min.js"></script>
<script src="../demo/js/bootstrap.js"></script>
<script src="../demo/js/bootstrap.min.js"></script>
<link href="../demo/css/bootstrap.css" rel="stylesheet">
<script src="../demo/js/employee_service.js"></script>
<script src="../demo/js/employee_controller.js"></script>
</head>
<body>
<form name="demo_form">
<div x-ng-controller="EmployeeController">
<h1> {{Employee.name}} </h1>
<span> </span>
<ul>
<li x-ng-repeat="address in employee.addresses">
{{address.address1}}
</li>
</ul>
</div>
</form>
</body>
</html>
This is my service script
var module = angular.module('demo', []);
module.service('EmployeeService', function($http){
this.get = function(id){
var method = "GET";
var url = "http://localhost:8080/rest/employee/get/" + id;
console.log(url);
$http({
method : method,
url : url,
headers: {'Content-Type' : 'application/json'}
}).then(onSuccess, onError);
function onSuccess(response){
console.log('got it');
return response.data;
}
function onError(response){
console.log(response.statusText);
}
}
});
This is my controller
//module.controller('EmployeeController', function ($scope, $routeParams EmployeeService) { //This line give an error but it is not related to the question
module.controller('EmployeeController', function ($scope, EmployeeService) {
//var paramEmployeeID = $routeParams.params1;
var paramEmployeeID = 1;
//Here it doesn't wait for the onSuccess method from the service which will deliver the object.
$scope.employee = EmployeeService.get(paramEmployeeID);
//$scope.employee = angular.copy(EmployeeService.get(paramEmployeeID));
console.log($scope.employee);
});
The error comes when the page loads and starts with the service and then controller. That's why it tries to load first the employee then it doesn't wait for the onSuccess method and it jumps to the controller to continue and finally comes back to the service to execute the onSuccess method which executes too late because it returns the object but in the controller I already got the undefined object. How can I solve this problem?
Async issue. You can chain the promise. Try:
On the service make sure you return the promise:
this.get = function(id){
var method = "GET";
var url = "http://localhost:8080/rest/employee/get/" + id;
console.log(url);
function onSuccess(response){
console.log('got it');
return response.data;
}
return $http({
method : method,
url : url,
headers: {'Content-Type' : 'application/json'}
}).then(onSuccess, onError);
}
In the controller you can chain it to get the data that you need:
EmployeeService.get(paramEmployeeID).then(function(employee){
$scope.employee = employee;
console.log($scope.employee);
});