How to pass Wordpress Json in angularjs - javascript

Hi guy i'm very new in angularjs and ionic.
I need to show the get json into html page.
How i can do that?
custom_fields: {
main_image: [
"11104,11102,11103"
],
image_backgrounds: [
null
],
videos_backgrounds: [
null
],
frontpage_listing_categories: [
null
],
geolocation_lat: [
"46.4090966"
],
This is my json return request.
How i can show on html for example : geolocation_lat?
I try to read documentation but i not understand.
Thank you
UPDATE:
HTML
<ion-view title="{{post.title}}">
<ion-nav-buttons side="right">
<a class="button button-clear" ng-click="sharePost()"><i class="icon ion-share"></i></a>
</ion-nav-buttons>
<ion-content class="has-header">
<div class="padding">
<h2 class="title">{{post.title}}</h2>
<div style="padding:0 0 20px 0;">
<!-- Posted {{post.date}} by <strong>{{post.author.name}}</strong><br/> -->
<!-- <em>Modified {{post.modified}}</em> -->
</div>
<p ng-show="{{post.attachments.length}}"><img ng-src="{{post.attachments[0].images.full.url}}"/></p>
<p ng-bind-html="content"></p>
<p ng-show="{{post.categories.length}}"><i class="icon ion-pricetags"></i>
<span ng-repeat="category in post.categories">{{category.title}} ({{category.post_count}}){{$last ? '' : ', '}}</span>
</p>
<p ng-show="{{post.tags.length}}"><i class="icon ion-pricetags"></i>
<span ng-repeat="tag in post.tags">{{tag.title}} ({{tag.post_count}}){{$last ? '' : ', '}}</span>
</p>
<p><button class="button icon-left ion-share button-outline button-positive" ng-click="sharePost()">Share this</button></p>
<!-- <button class="button button-full button-positive" ng-click="loadURL(post.url)">
View post
</button> -->
</div>
</ion-content>
APP.JS
.factory('PostsData', function($http, $q, PostsStorage, API) {
var json = API + '/api/get_recent_posts/';
var deferred = $q.defer();
var promise = deferred.promise;
var data = [];
var service = {};
service.async = function() {
$http({method: 'GET', url: json, timeout: 5000}).
// this callback will be called asynchronously
// when the response is available.
success(function(d) {
data = d;
PostsStorage.save(data);
deferred.resolve();
}).
// called asynchronously if an error occurs
// or server returns response with an error status.
error(function() {
data = PostsStorage.all();
deferred.reject();
});
return promise;
};
service.getAll = function() { return data; };
service.get = function(postId) { return data.posts[postId]; };
return service;
})
.factory('ServerPostsData', function($http, $q, ServerPostsStorage, API) {
var data = [];
var service = {};
/* (For DEMO purposes) Local JSON data */
// var json = 'json/serverposts&';
/* Set your URL as you can see in the following example */
/* NOTE: In case of the default permalinks, you should add '&' at the end of the url */
// var json = 'YourWordpressURL/?json=get_recent_posts&';
/* With user-friendly permalinks configured */
/* NOTE: In case of the user-friendly permalinks, you should add '?' at the end of the url */
var json = API + '/api/jobs/get_job_listing?';
service.getURL = function() { return json; };
service.setData = function(posts) { data = posts; };
service.get = function(serverpostId) { return data[serverpostId]; };
return service;
})
COTROLLER.JS
// ServerPosts Controller
.controller('ServerPostsCtrl', function($scope, $http, $ionicLoading, ServerPostsData, ServerPostsStorage) {
var data = []
$scope.posts = [];
$scope.storage = '';
$scope.loading = $ionicLoading.show({
template: '<i class="icon ion-loading-c"></i> Loading Data',
//Will a dark overlay or backdrop cover the entire view
showBackdrop: false,
// The delay in showing the indicator
showDelay: 10
});
$scope.loadData = function () {
$http({method: 'GET', url: ServerPostsData.getURL() + 'page=' + $scope.page, timeout: 5000}).
// this callback will be called asynchronously
// when the response is available.
success(function(data) {
$scope.more = data.pages !== $scope.page;
$scope.posts = $scope.posts.concat(data.posts);
ServerPostsData.setData($scope.posts);
ServerPostsStorage.save(data);
$ionicLoading.hide();
}).
// called asynchronously if an error occurs
// or server returns response with an error status.
error(function() {
$scope.posts = ServerPostsStorage.all().posts;
ServerPostsData.setData(ServerPostsStorage.all().posts);
$scope.storage = 'Data from local storage';
$ionicLoading.hide();
});
};
$scope.showMoreItems = function () {
$scope.page += 1;
$ionicLoading.show({
template: '<i class="icon ion-loading-c"></i> Loading Data',
//Will a dark overlay or backdrop cover the entire view
showBackdrop: false,
// The delay in showing the indicator
showDelay: 10
});
$scope.loadData();
}
$scope.hasMoreItems = function () {
return $scope.more;
}
$scope.page = 1;
$scope.more = true;
$scope.loadData();
})
// ServerPost Controller
.controller('ServerPostCtrl', function($scope, $stateParams, ServerPostsData, $sce) {
$scope.post = ServerPostsData.get($stateParams.serverpostId);
$scope.content = $sce.trustAsHtml($scope.post.content);
$scope.loadURL = function (url) {
//target: The target in which to load the URL, an optional parameter that defaults to _self. (String)
//_self: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the InAppBrowser.
//_blank: Opens in the InAppBrowser.
//_system: Opens in the system's web browser.
window.open(url,'_blank');
}
$scope.sharePost = function () {
var subject = $scope.post.title;
var message = $scope.post.content;
message = message.replace(/(<([^>]+)>)/ig,"");
var link = $scope.post.url;
//Documentation: https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin
//window.plugins.socialsharing.share('Message', 'Subject', 'Image', 'Link');
window.plugins.socialsharing.share(message, subject, null, link);
}
})

Related

displaying data ng-repeat from $scope.items query not working

I do not know what is wrong, ng-repeat is not
populating the information on my div, please look at the following
and advice where I have gone wrong
app.js
var mainApp = angular.module('mainApp', ["ngRoute", "ngResource"]);
mainApp.factory('EventListFactory',['$resource', EventListFactory]);
mainApp.controller('EventListCtrl', ['$scope','EventListFactory', EventListCtrl]);
var configFunction = function ($routeProvider) {
$routeProvider.
when('/Register', {
templateUrl: 'routesDemo/Register'
})
.when('/UpdateProfile', {
templateUrl: 'routesDemo/UpdateProfile'
})
.when('/Events', {
templateUrl: 'routesDemo/Events',
controller: EventListCtrl,
})
.when('/routeThree', {
templateUrl: 'routesDemo/three'
});
}
configFunction.$inject = ['$routeProvider'];
mainApp.config(configFunction);
EventListFactory.js
var EventListFactory = function ($resource, $location) {
var baseUrl = "";
if (window.location.hostname == 'localhost') {
baseUrl = "http://localhost:52182/api/Events/GetEvents/";
}
else
{
var deployAt = window.location.href.substring(0, window.location.href);
baseUrl = deployAt + "/api/Events/GetEvents";
}
var respone = $resource(baseUrl, null, { query: { method: 'GET', isArray: true, url: baseUrl }, get: { method: 'GET', url: baseUrl } });
console.log("api json at :" + baseUrl);
var records = respone.query();
console.log(records);
return records;
}
EventListController.js
var EventListCtrl = function ($scope, EventListFactory) {
$scope.Message = 'I work';
$scope.items = EventListFactory;
};
EventListCtrl.$inject = ['$scope'];
in the html:
<div id="listView" >
<h1 class="form-signin-heading">For real {{Message}}</h1>
<div ng-controller="EventListCtrl">
<p class="form-signin-heading">Populated Data</p>
<div ng-repeat="item in items ">
<span class="control-label">Heading : </span> {{item.Heading}}
<br/>
<span class="control-label">Event Date : </span> {{item.EventDate}}
<br/>
</div>
</div>
</div>
running the site:
api call from browser:
the code for ng-repeat is correct, but your items is an empty array so nothing gets displayed.
From the screenshots it appears that records in EventListFactory.js does not return an array but a promise.
In EventListController.js instead of
$scope.items = EventListFactory;
Try something like:
var promise = EventListFactory;
promise.then(function(data){
$scope.items = data;
})

Angular form submission not displaying results from PHP

I'm trying to display the results from a submitted form, AngularJS > PHP > Back but I'm getting nothing. I've tried a lot of different ways and according to all of google I'm doing it right but the console log just says that it's undefined.
Here is the submit function:
$scope.testProcessForm = function() {
$http({
method : 'POST',
url : 'test.php',
data : $scope.formData,
headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
})
.success(function(data) {
if (data.errors) {
// Showing errors.
$scope.errorselectedServices = data.errors.selectedservices;
$scope.errorincEmail = data.errors.incemail;
} else {
$scope.submissionMessage = data.messageSuccess;
$scope.test= data.test;
The PHP:
$data['test'] = $test;
echo json_encode($data);
HTML:
<div ng-show="test">{{test}}</div>
Why am I getting "test is undefined" and no div? If I put an echo into PHP I get the proper reply back. It doesn't appear to hang anywhere in the code after some debugging. What am I doing wrong?
// app.js
// create our angular app and inject ngAnimate and ui-router
// =============================================================================
angular.module('formApp', ['ngAnimate', 'ngMessages', 'ui.router'])
// configuring our routes
// =============================================================================
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show our basic form (/form)
.state('form', {
url: '/form',
templateUrl: 'form.html',
controller: 'formController'
})
// nested states
// each of these sections will have their own view
// url will be nested (/form/profile)
.state('form.tjanst', {
url: '/tjanst',
templateUrl: 'form-tjanster.html'
})
// url will be /form/interests
.state('form.epost', {
url: '/epost',
templateUrl: 'form-epost.html'
})
// url will be /form/payment
.state('form.fax', {
url: '/fax',
templateUrl: 'form-fax.html'
})
// url will be /form/payment
.state('form.sms', {
url: '/sms',
templateUrl: 'form-sms.html'
})
// url will be /form/payment
.state('form.mcl', {
url: '/mcl',
templateUrl: 'form-mcl.html'
})
// url will be /form/payment
.state('form.review', {
url: '/review',
templateUrl: 'form-review.html'
});
// catch all route
// send users to the form page
$urlRouterProvider.otherwise('/form/tjanst');
})
.value('formSteps', [
{uiSref: 'form.tjanst', valid: false},
{uiSref: 'form.epost', valid: false},
{uiSref: 'form.fax', valid: false},
{uiSref: 'form.sms', valid: false},
{uiSref: 'form.mcl', valid: false},
{uiSref: 'form.review', valid: false}
])
.run([
'$rootScope',
'$state',
'formSteps',
function($rootScope, $state, formSteps) {
// Register listener to watch route changes
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
var canGoToStep = false;
// only go to next if previous is valid
var toStateIndex = _.findIndex(formSteps, function(formStep) {
return formStep.uiSref === toState.name;
});
console.log('toStateIndex',toStateIndex)
if(toStateIndex === 0) {
canGoToStep = true;
} else {
canGoToStep = formSteps[toStateIndex - 1].valid;
}
console.log('canGoToStep', toState.name, canGoToStep);
// Stop state changing if the previous state is invalid
if(!canGoToStep) {
// Abort going to step
event.preventDefault();
}
});
}
])
// our controller for the form
// =============================================================================
.controller('formController', function($scope, $state, $http, formSteps) {
// we will store all of our form data in this object
$scope.formData = {};
$scope.submission = false;
$scope.formStepSubmitted=false;
$scope.formData.selectedServices = {};
$scope.messitServices = [{'name':'Fax', 'id':1}, {'name':'SMS', 'id':2}, {'name':'Minicall', 'id':3}];
$scope.someSelected = function (object) {
return Object.keys(object).some(function (key) {
return object[key];
});
};
var nextState=function(currentState) {
switch (currentState) {
case 'form.tjanst':
return 'form.epost'
break;
case 'form.epost':
return 'form.fax'
break;
case 'form.fax':
return 'form.sms'
break;
case 'form.sms':
return 'form.mcl'
break;
case 'form.mcl':
return 'form.review'
break;
default:
alert('Did not match any switch');
}
};
var updateValidityOfCurrentStep=function(updatedValidity) {
var currentStateIndex = _.findIndex(formSteps, function(formStep) {
return formStep.uiSref === $state.current.name;
});
formSteps[currentStateIndex].valid = updatedValidity;
};
$scope.goToNextSection=function(isFormValid) {
console.log('isFormValid ', isFormValid);
// set to true to show all error messages (if there are any)
$scope.formStepSubmitted = true;
if(isFormValid) {
// reset this for next form
$scope.formStepSubmitted = false;
// mark the step as valid so we can navigate to it via the links
updateValidityOfCurrentStep(true /*valid */);
$state.go(nextState($state.current.name));
} else {
// mark the step as valid so we can navigate to it via the links
updateValidityOfCurrentStep(false /*not valid */);
}
};
$scope.testProcessForm = function() {
$http({
method : 'POST',
url : 'kundreg.php',
data : $scope.formData,
headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
})
.success(function(data) {
if (data.errors) {
// Showing errors.
$scope.errorselectedServices = data.errors.selectedservices;
$scope.errorincEmail = data.errors.incemail;
} else {
$scope.submissionMessage = data.messageSuccess;
$scope.faxSenderPhoneNo = data.faxSenderPhoneNo;
$scope.faxSender = data.messit.faxSender;
console.log(faxSender);
// $scope.formData = {};
}
});
};
});
<!DOCTYPE html>
<h3 class="text-center">Granskning</h3>
<h4 class="text-center">Vänligen kontrollera:</h4><br>
<div class="form-group row"></div>
<!-- <span ng-show="errorselectedServices">{{errorselectedServices}}</span>
<span ng-show="errorincEmail">{{errorincEmail}}</span>></div> -->
<div ng-show="faxSender">{{ faxSender }} ng show faxsenderphoneno</div>
<br>
<div class="form-group row">
<div class="col-xs-6 col-xs-pull">
<a ui-sref="form.fax" class="btn btn-block btn-info">
Föregående <span class="glyphicon glyphicon-circle-arrow-left"></span></a>
</div>
<div class="col-xs-6 col-xs-push">
<a ng-click="testProcessForm()">
Skapa <span class="glyphicon glyphicon-circle-arrow-right"></span>
</a>
</div>
</div>
<?php
$errors = array();
$data = array();
$selectedServices = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);
// checking for blank values.
if (empty($_POST['selectedServices']))
$errors['selectedServices'] = 'Minst en tjänst måste väljas.';
if (empty($_POST['incEmail']))
$errors['incEmail'] = 'Epost som tillåts använda tjänsterna saknas';
$selectedServices = $_POST['selectedServices'];
if (!empty($errors)) {
$data['errors'] = $errors;
} else {
if (!empty($_POST["faxSenderPhoneNo"])) {
// ta bort allt som inte är siffror
$faxSender = preg_replace('/[^0-9\/+]/', '', $_POST["faxSenderPhoneNo"]);
// finns ingen nolla så lägger vi till den så vi kan matcha den i regexen
//regex med internationellt format så databasen blir glad
if (preg_match('/^0/', $faxSender) === 0) {
$faxSender = "0{$faxSender}";
}
$faxSenderPhoneNo = preg_replace("/(^0|^46)/", "+46", $faxSender);
$messit['faxSender'] = $faxSenderPhoneNo;
}
else {
$faxSenderPhoneNo = 'NULL';
}
if (!empty($_POST["deliveryReportFax"])) {
$deliveryReportFax = $_POST["deliveryReportFax"];
}
else {
$deliveryReportFax = '3';
}
}
}
if (!$error) {
// sql
echo json_encode($data);
?>
I found the error. Apparently you have to quote the variable into the array;
$data['faxSender'] = "$faxSenderPhoneNo";
Now works as intended.
EDIT:
Well it worked to a point. My divs still weren't displaying. After logging with console.log(data) I could see that I had a lot of undefined indexes but my data array was there so I didn't understand why I couldn't access it.
I fixed the undefined stuff and then suddenly every div was displayed. Not a clue why PHP decides to dump all that info into my $data array.
2nd edit: Apparently .success is deprecated. Using .then instead with error_reporting(1); seems to always give me an array with data that angular then can use.
Since you are JSON encoding data in php file, file returning a String. so, you will need decode JSON to Java script object first. Also, you $http returns angular promise($q service). I am not sure about using
.success
method. Instead use
.then
.then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
// decode JSON firs since you are sending JSON from PHP
var data = JSON.parse(response);
$scope.test = data.test;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
// Handle error here
});

Delay directive/div until scope value available

I have a custom directive for soundcloud that requires the soundcloud url. The soundcloud url is fetched from the database through the $http service, however, the div for the soundcloud custom directive is loaded and requires the value of the soundcloud url before it is even defined.
The Plangular Directive Code I got is here:
https://github.com/jxnblk/plangular/blob/master/src/plangular.js *I did not develop this
This is my HTML code:
<div plangular="{{soundcloud}}">
<button ng-click="playPause()">Play/Pause</button>
<progress ng-value="currentTime / duration || 0">
{{ currentTime / duration || 0 }}
</progress>
</div>
And this is the Angular Code:
displaySong.controller('song', ['$scope', '$http', 'fetchSong', function($scope, $http, fetchSong) {
$scope.songID
$scope.songName;
//Controller properties
$scope.songPromise; //The song promise for fetching
$scope.init = function(songID, userID) {
$scope.songID = songID;
$scope.userID = userID;
$scope.songPromise = $http({
method: "post",
url: fetchSong,
data: {
song_id: $scope.songID
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function(successResponse) {
console.log('Successfully fetched song');
console.log(successResponse);
var song = successResponse.data;
$scope.songID = song.song_id;
$scope.songName = song.song_name;
$scope.songType = song.song_type;
$scope.songEmbed = song.song_embed;
$scope.soundcloud = song.song_embed;
}, function(errorResponse) {
console.log('Error fetching');
$scope.songID = null;
});
};
}]);
I know it's a problem with the asynchronous nature because when I add this line in the beginning of my song controller:
$scope.soundcloud = "https://soundcloud.com/jshigley/shine";
It works perfectly fine. I've also noticed that when I spam the play/pause button that DOES come up from the directive, I get multiple console errors of "HTTP 404 Not Found", which leads me to believe it's trying to find a track of undefined url
Since it's a div directive and not a function call I can't use promises such as chaining a then to my $scope.songPromise. I've thought of putting it into a controller and having the controller do something like $timeout for 5 seconds, but I don't think this delays the execution of the DOM.
The soundcloud URL DOES end up getting loaded, but it remains undefined in the eyes of the plangular directive (I've actually encountered lots of these problems with bad timing of loading scope and directives). Any Angular Wizards willing to teach me how to tame the asynchronous nature of AngularJS?
You can use $watch in the custom directive to watch when url attributes is changed.
In
link: function(scope, el, attr) {
change from
if (src) {
resolve({ url: src, client_id: client_id }, function(err, res) {
if (err) { console.error(err); }
scope.$apply(function() {
scope.track = createSrc(res);
if (Array.isArray(res)) {
scope.tracks = res.map(function(track) {
return createSrc(track);
});
} else if (res.tracks) {
scope.playlist = res;
scope.tracks = res.tracks.map(function(track) {
return createSrc(track);
});
}
});
});
}
to
scope.$watch('attr.plangular', function(newVal) {
resolve({ url: attr.plangular, client_id: client_id }, function(err, res) {
if (err) { console.error(err); }
scope.$apply(function() {
scope.track = createSrc(res);
if (Array.isArray(res)) {
scope.tracks = res.map(function(track) {
return createSrc(track);
});
} else if (res.tracks) {
scope.playlist = res;
scope.tracks = res.tracks.map(function(track) {
return createSrc(track);
});
}
});
});
}, true);
If you dont want to change the directive then you might want to use ng-if to load that plangular div only when you get the url.
<div plangular="{{soundcloud}}" ng-if="haveurl">
and in the angular code :
}).then(function(successResponse) {
console.log('Successfully fetched song');
console.log(successResponse);
$scope.haveurl = true;
Try using ng-show like this to only show the div once your $http request has been completed.
<div ng-show="httpRequestComplete" plangular="{{soundcloud}}">
<button ng-click="playPause()">Play/Pause</button>
<progress ng-value="currentTime / duration || 0">
{{ currentTime / duration || 0 }}
</progress>
</div>
displaySong.controller('song', ['$scope', '$q', '$http', 'fetchSong', function($scope, $http, fetchSong) {
/* add $q promise library */
$scope.songID
$scope.songName;
var httpRequest = function() {
var deferred = $q.defer();
$http({
method: "post",
url: fetchSong,
data: {
song_id: $scope.songID
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(successResponse) {
deferred.resolve({response: successResponse});
console.log('Successfully fetched song', successResponse);
var song = successResponse.data;
$scope.songID = song.song_id;
$scope.songName = song.song_name;
$scope.songType = song.song_type;
$scope.songEmbed = song.song_embed;
$scope.soundcloud = song.song_embed;
}).error(function(error) {
console.log(error);
});
return deferred.promise;
};
httpRequest().then(function(response) {
$scope.httpRequestComplete = true;
console.log('div will show');
};
}]);
I would do something like this that delays the showing of the div until httpRequestComplete = true, or until your promise ($q) is fulfilled. This will make sure that your div isn't loaded until you have the information available.

Revealing module for AJAX Angular Service

Below I've got an angular app and controller where the controller have data access inside of it (bad idea, I know)
var app = angular.module('app',[]);
app.controller('HomeController',function($scope,$http){
$scope.people = null;
$scope.get = function() {
$http({
url: 'largeTestData.json',
method: 'GET'
}).then(function(data){
console.log('request successful, here is your data: ');
console.log(data['data']);
$scope.people = data['data'];
},function(reason){
console.log('this failed, this is the reason: ');
console.log(reason);
})
}
});
app.controller('ControllerWithService',function($scope, MyService){
$scope.get = MyService.get;
$scope.get(function(data){
console.log('you succeeded');
},function(reason){
console.log('you failed');
console.log(reason);
})
})
This will work in retrieving data and putting it onto the page. Knowing that having data Access in the controller is no bueno I tried to abstract that out into a service:
app.service('MyService',function($http,$q){
var get = function(){
var deferred = $q.defer();
var url = 'test.json';
$http.get(url).success(deferred.resolve).error(deferred.reject);
}
return {
get: get
}
})
Here my 'data layer' is a service that only has one method: get from the above listed URL.
app.service('MyService',function($http,$q){
var get = function(){
var deferred = $q.defer();
var url = 'test.json';
$http.get(url).success(deferred.resolve).error(deferred.reject);
}
return {
get: get
}
})
and my HTML
<body>
<script src="libs/angular-1.2.15.js"></script>
<script src="app/app.js"></script>
<script src="app/DocumentService.js"></script>
<script src="libs/jQuery-2.1.1.js"></script>
<div ng-controller="HomeController">
<button ng-click="get()" href="#">Get data</button>
<div>{{message}}</div>
<!--<div ng-repeat="p in people" >-->
<!--<b>Business Doc ID: </b><h1>{{p['busDocId']}}</h1>-->
<!--<b>DOC ID: </b>{{p['docId']}}-->
<!--<b>FILE NAME: </b><div style="color: green">{{p['fileName']}}</div>-->
<!--</div>-->
</div>
<div ng-controller="ControllerWithService">
{{message}}
<button ng-click="get()">get data</button>
<div>{{data}}</div>
</div>
</body>
I'm not getting any error messages, and the commented out out stuff in my HomeController works as expected. What am I doing wrong in trying to make my AJAX calls a service?
working solution changes:
app.service('MyService',function($http,$q){
this.get = function(){
return $http.get('test.json')
}
})
app.controller('ControllerWithService',function($scope, MyService){
$scope.data = null;
$scope.get = function() {
MyService.get().then(function (data) {
console.log('this is the success data: ');
console.log(data)
$scope.data = data;
}, function (reason) {
console.log('this is the fail reason');
console.log(reason);
$scope.data = reason;
})
}
})
It looks like it could be a couple different things. I'll post an example I have working in one of my projects right now. It should be extremely similar and simple with what you're goal is.
Service:
'use strict';
angular.module('srcApp')
.service('Getlanguage', function Getlanguage($location, $http, $log, $state, $rootScope) {
this.getContent = function() {
var language = $location.path().split('/'),
languageCulture = language[1];
if (!languageCulture) {
languageCulture = 'en';
}
$rootScope.cultureCode = languageCulture;
return $http({method: 'GET', url: '/languages/' + languageCulture + '.json'})
.error(function() {
// If service cannot find language json file, redirect to index
$state.go('lang', {lang: 'en'});
});
};
});
Controller Call to service:
After passing in the service as a dependency into the controller.
Getlanguage.getContent().then(function(res) {
$scope.content = res.data;
});
Hope this helps.

Angular ui grid how to show a loader

I'm wondering how to show a simple loader before data was loaded.
I'm using ng-grid-1.3.2
I'm googling but I didn't find any example.
Bye
like Maxim Shoustin suggested you can use the angularjs-spinner from Jim Lavin which uses (deprecated) Response Interceptors.
I think it's explained best here :
http://codingsmackdown.tv/blog/2013/04/20/using-response-interceptors-to-show-and-hide-a-loading-widget-redux/
In a nutshell, in his first solution, what you have to do for your ng-grid app is:
1) Add the loading gif to your html (for loading gif look here)
<div id="loadingWidget" class="row-fluid ui-corner-all" style="padding: 0 .7em;" loading-widget >
<div class="loadingContent">
<p>
<img alt="Loading Content" src="images/ajax-loader.gif" /> Loading
</p>
</div>
</div>
2) In your code as soon as you have declared your app level module add the Response Interceptors for http requests to the configuration block
var app = angular.module('myCoolGridApp', ['ngGrid']);
app.constant('_START_REQUEST_', '_START_REQUEST_');
app.constant('_END_REQUEST_', '_END_REQUEST_');
app.config(['$httpProvider', '_START_REQUEST_', '_END_REQUEST_', function ($httpProvider, _START_REQUEST_, _END_REQUEST_) {
var $http,
interceptor = /* see extra details on codingsmackdown.tv */
$httpProvider.responseInterceptors.push(interceptor);
}
3) and then add your loadingWidget directive
app.directive('loadingWidget', ['_START_REQUEST_', '_END_REQUEST_', function (_START_REQUEST_, _END_REQUEST_) {
return {
restrict: "A",
link: function (scope, element) {
element.hide();
scope.$on(_START_REQUEST_, function () {element.show();});
scope.$on(_END_REQUEST_, function () {element.hide();});
}
};
}]);
See more details at codingsmackdown
I had the same question as you.
I find this nice tutorial about it: http://brianhann.com/ui-grid-the-easiest-customization-youll-ever-write/
He use vm.loading = true while fetching data from server and changed to false after complete.
var app = angular.module('app', ['ngTouch', 'ui.grid']);
app.controller('MainCtrl', ['$http', '$timeout', function ($http, $timeout) {
var vm = this;
vm.reset = reset;
vm.noData = noData;
vm.gridOptions = {
columnDefs: [
{ field: 'name' },
{ field: 'age' }
]
};
reset();
////////////
// Initialize our data source
function init() {
$http.get('data.json')
.success(function (data) {
vm.gridOptions.data = data;
})
.finally(function () {
vm.loading = false;
});
}
// Reset the data source in a timeout so we can see the loading message
function reset() {
vm.loading = true;
vm.gridOptions.data = [];
$timeout(function () {
init();
}, 1000);
}
function noData() {
vm.gridOptions.data = [];
}
}]);
In the HTML, he uses ng-hide to show/hide the spinner based on values of gridOptions.data and vm.loading:
<div id="grid1" ui-grid="vm.gridOptions" class="grid">
<div class="grid-msg-overlay" ng-hide="!vm.loading">
<div class="msg">
<span>
Loading Data...
<i class="fa fa-spinner fa-spin"></i>
</span>
</div>
</div>
<div class="grid-msg-overlay" ng-hide="vm.loading || vm.gridOptions.data.length">
<div class="msg">
<span>No Data</span>
</div>
</div>
</div>
Here is the Plunker of the final version shown.
You have angularjs-spinner, see GitHub sources
I also needed a similar behavior and I came across this answer but I needed to show something inside the grid itself so here is something I put together. My idea is that I change the gridOptions on the fly and show a loader as a row inside the grid.
loaderOptions = {
"columnDefs": [{
"name": "",
"field": "loading",
"enableColumnMenu": false,
"cellTemplate": '<div style="width:90px; margin:auto;"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Loading...</div>'
}],
"data": [{
"loading": ""
}]
};
Simply,by adding this code in your html part:
<img alt="loading..." src='images/ajax-loader.gif")' /> loading message...
and the following code in your app.controller script:
$http.get(yourdataUrl)
.then(function (response) {
$scope.records = response.data;
$("#loadingWidget").hide();
});
it works fine for me!
The HTML code-sample
<img ng-show="loading" src="~/img/loding.jpg" />
<div class="ngtyle" ng-grid="myGridView"></div>
The AngularJs code-sample
var app = angular.module('App', ['ngGrid']);
app.controller('MainCtrl', function ( $scope, myService ) {
$scope.loading = true;
myService.get().then( function ( response ) {
$scope.items = response.data;
})
.finally(function() {
$scope.loading = false;
});
$scope.myGridView = {
data: 'dataList',
columnDefs: 'myDisplayColumns'};
});

Categories