angular js view render delay with ng-repeat - javascript

I have a view that renders posts it gets from a factory,
my problem is that the view is delayed only after all the posts are rendered.
You can see the video here:
https://www.youtube.com/watch?v=aFHiqrtV10w
The code sample:
as you can see the code has a function "loadPosts", and just after I call this function.
Just for loading the posts.
app.controller('postsPageController', ['$scope', '$ionicModal', 'Posts', 'Comments', '$ionicLoading', 'Cache', '$timeout', 'Security',
function ($scope, $ionicModal, Posts, Comments, $ionicLoading, Cache, $timeout, Security) {
$scope.posts = [];
$scope.loadPosts = function(noCache) {
$http({method: 'POST', url: BloompyService.url()+'api/posts/all'})
.success(function(data) {
$scope.posts = data;
}).error(function(data) {
console.log('error');
});
$scope.init = function () {
$scope.loadPosts(false);
};
$scope.init();
}

Related

AngularJS: How to fetch data of specific id from JSON file

In my controller class I fetch the id of specific user from URL and then send it to service OrderService Now in the service I want to retrieve the data of this id from JSON file , How can I achieve this ?
OrderCtrl
'use strict';
angular.module('Orders').controller('OrderCtrl', ['$scope', '$state', "SettingService", "OrderService","$stateParams", function($scope, $state, SettingService, OrderService,$stateParams) {
var OrderId = $stateParams.orderId;
$scope.orders = [];
OrderService.getOrderDetails(OrderId).then(function(response){
$scope.orders = response.data.data;
}, function(error){
})
}]);
OrderService.js
angular.module('Orders')
.service('OrderService', ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService",
function($http, $state, $resource, $q, SettingService, $localStorage, MessageService) {
var service = {
getOrderDetails : function(OrderId){
Here I want to retrieve data from JSON file
});
}
}
return service;
}]);
Try to use something like this
'use strict';
angular.module('Orders').controller('OrderCtrl', ['$scope', '$state', "SettingService", "OrderService", "$stateParams", function ($scope, $state, SettingService, OrderService, $stateParams) {
var OrderId = $stateParams.orderId;
$scope.orders = [];
OrderService.getOrderDetails(OrderId).then(function (response) {
$scope.orders = response.data.data;
});
}]);
// I act a repository for the remote json collection.
angular.module('Orders').service("OrderService", ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService",
function ($http, $state, $resource, $q, SettingService, $localStorage, MessageService, handleResponse) {
// Return public API.
return ({
getOrderDetails: getOrderDetails
});
// I get all the remote collection.
function getOrderDetails(OrderId) {
var request = $http({
method: "get",
url: '/ajax/order/details', // for example
params: {'id': OrderId}
});
return (request.then(handleResponse.success, handleResponse.error));
}
}]);
angular.module('Orders').service('handleResponse', function ($http, $q, $location) {
return {
error: function (response) {
// The API response from the server should be returned in a
// nomralized format. However, if the request was not handled by the
// server (or what not handles properly - ex. server error), then we
// may have to normalize it on our end, as best we can.
if (!angular.isObject(response.data) || !response.data.message) {
// Something was wrong, will try to reload
return ($q.reject("An unknown error occurred."));
}
// Otherwise, use expected error message.
return ($q.reject(response.data.message));
},
success: function (response) {
return (response.data);
}
};
});

Angular ui-route with JSON Data Request

I want to build a Single Page Website, where my data is stored in a CMS. This CMS accepts Ajax Requests to serve me JSON. This JSON I want to output in my ng-app using the ui-router (I also tried the ngRoute before, with same results).
The Problem is: I need no template. Cause all my data I need comes from the JSON Request. But using no template or templateUrl doesn't affects the controller.
The question is how to output my received data in the HTML? I cant use ng-controller because it binds on only this specific controller. Console.log shows that my data is successfully received, but I found no way to get an output.
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise("/");
$stateProvider
.state('state1', {
url: '/state1',
template: '<h1>This Is A State</h1>',
controller: function($scope, $http) {
$scope.pageObj = '';
$scope.pageObj.url = '/angular/demo/';
$scope.pageObj.class = 'page-my';
$scope.pageObj.data = 'Empty';
$http
.get('/angular/demo/')
.then(function(result) {
console.log("Data Received");
console.log(result.data);
$scope.pageObj.data = result.data;
});
//console.log(result.data);
console.log("Hello state");
}
});
});
I found a small solution with using factory. The question is still, how do I access my data? Data now is stored by an own controller i guess. I post my updated code below:
var app = angular.module('myApp', ['ngSanitize', 'ngRoute', 'ui.router']).factory("dataService", function($http) {
var data = "";
var getData = function() {
return data;
}
var setData = function(newData) {
data = newData;
}
return {
getData: getData,
setData: setData
};
});
app.controller('FactoryCtrl', ['$scope', '$http', 'dataService', function($scope, $http, dataService) {
$scope.mydata = dataService.getData();
console.log($scope.mydata);
}]);
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise("/");
$stateProvider
.state('state1', {
url: '/state1',
template: '<h1>{{pageObj.data}}</h1>',
controller: function($scope, $http, dataService) {
$scope.pageObj = '';
$scope.pageObj.url = '/angular/demo/';
$scope.pageObj.class = 'page-my';
$scope.pageObj.data = 'Empty';
$http
.get('/angular/demo/')
.then(function(result) {
console.log("Data Received");
$scope.pageObj.data = result.data;
//$scope.model.data = dataService.getData();
dataService.setData("a string");
//console.log(dataService.getData());
});
console.log("Hello state");
}
});
});

$location.path same url not working

Below is my code:
app.controller('lookupMasterController', [
'$scope', '$routeParams', '$location', '$modal', 'lookupService', function ($scope, $routeParams, $location, $modal, lookupService) {
$scope.openCreatePopup = function () {
var modalInstance = $modal.open({
animation: true,
templateUrl: 'app/popups/add-lookup.html',
controller: function ($scope, $modalInstance, $location, $routeParams, lookupService) {
$scope.cancel = function () {
$modalInstance.close();
}
$scope.addLookup = function () {
$scope.lookup.lookUpConfigId = $routeParams.lookupMasterId;
lookupService.save($scope.lookup).$promise.then(
function (value) {
$location.path('/edit-lookup/' + $routeParams.lookupMasterId);
$scope.$apply();// Even this is not working.
// Tried the below as well:
//$scope.$apply(function () {
// $location.path('/edit-lookup/' + //$routeParams.lookupMasterId);
// });
$modalInstance.close();
},
function (error) { /*Do something with error*/
alert(error.message);
});
}
},
size: 'lg'
});
}
}
]);
I am opening a Popup for add new lookup and then reloading the page to see the changes. But the problem is : $location.path('url'); is not working.
You should use $state service in that case. Try
$state.go('/edit-lookup/' + $routeParams.lookupMasterId);
Don't forget to inject $state in your controller initilization. Plus in your module definition you need to pass 'ui.router' as a dependency :
E.g. angular.module('my_app', ['ui.router'])
EDIT
I think you didn't load ui-router.min in your web page. Please load it just after angular.js
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>

AngularJS $scope.foo is set with service, but later on in the same controller undefined

I have a service which calls API and gets json response. I inject this service into my controller and try to set $scope.tank variable with this received data. When I try to use this variable later on (in the same controller!) it is undefined. But the funny thing is that data is displayed in the front-end.
I've looked all over stackoverflow and I can not figure this out. I have created a plunker example - http://plnkr.co/edit/DkFNE8E9897dSF19eaU9?p=preview
My service:
appServices.service('TankService', function($q, $http) {
var data, deferred = $q.defer();
return {
init: function(id) {
var defer = $q.defer();
$http.get(options.api.base_url, { cache: 'true'})
.success(function(response) {
data = response;
deferred.resolve(data);
});
},
// return promise
getData: function() {
return deferred.promise;
}
};
});
I call my data in controller like this:
appControllers.controller('TankViewCtrl', ['$rootScope', '$scope', '$q', '$routeParams', '$location', '$sce', '$route', 'TankService',
function TankViewCtrl($rootScope, $scope, $q, $routeParams, $location, $sce, $route, TankService) {
var id = $routeParams.tank_id;
$scope.id = id;
$scope.tank = [];
// call our data
TankService.init(id);
TankService.getData().then(function(data){
$scope.tank = data;
});
// why is this undefined?
console.log($scope.tank);
}
]);
Thank in advance for your help!
HTTP calls are asynchronous requests.
You're asking your controller to display the result of the request without making sure you had an answer beforehand. That's why you get undefined.
Use :
TankService.getData().then(function(data){
$scope.tank = data;
console.log($scope.tank);
});

AngularJS - Using $resource and interact with a RESTful data source

I've had a problem in my previous topic, that I couldn't consume my service.
After doing some research I could finally figure out a way to consume my service after all. Still I was wondering why my other approach with the javascript object as method container didn't work out. I have some guesses but can't find an appropriate solution.
Hopefully you guys can lead me on the right path.
controller.js (Working solution)
angular.module('TodoApp.controllers', []).
controller('listCtrl', function ($scope, $location, todoApiService) {
$scope.todos = todoApiService.query();
});
services.js (Working solution)
angular.module('TodoApp.services', []).
factory('todoApiService', function ($resource) {
return $resource('/api/todo/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
controllers.js (Not working solution)
angular.module('TodoApp.controllers', []).
controller('listCtrl', function ($scope, $location, todoApiService) {
$scope.todos = todoApiService.getMyTodos.query();
});
services.js (Not working solution)
angular.module('TodoApp.services', []).
factory('todoApiService', function () {
var todoApi = {};
todoApi.getMyTodos = function ($resource) {
return $resource('/api/todo/:id', { id: '#id' }, { update: { method: 'PUT' } });
};
return todoApi;
});
You should either:
Inject $resource to your factory function, just like you did in the working version. And then you can remove the $resource as a parameter for getMyTodos.
angular.module('TodoApp.services', []).
factory('todoApiService', function ($resource) {
var todoApi = {};
todoApi.getMyTodos = function () {
return $resource('/api/todo/:id', { id: '#id' }, { update: { method: 'PUT' } });
};
return todoApi;
});
And then from the controller:
angular.module('TodoApp.controllers', []).
controller('listCtrl', function ($scope, $location, todoApiService) {
$scope.todos = todoApiService.getMyTodos().query();
});
Or, you can pass the $resource from the controller to getMyTodos (after injecting it to the controller) - so your controller would look like:
angular.module('TodoApp.controllers', []).
controller('listCtrl', function ($scope, $location, todoApiService, $resource) {
$scope.todos = todoApiService.getMyTodos($resource).query();
});
I didn't check to see that this is working, but it should :)

Categories