AngularJS: Loading single objects from json - json

I'm trying to list some posts from a json file then after click one, load the single post, but when I click it the data is not loaded.
I'm using the function below to handle the data
$scope.currentPost = $filter('filter')($scope.posts, {id: $routeParams.id})
Here is my Plnkr: http://plnkr.co/edit/brWn6r4UvLnNY5gcFF2X?p=preview

Updated Plnkr: http://plnkr.co/edit/3P2k60aPyuatjTx9raJU?p=preview
app.controller('MainCtrl', function($scope, $http, $route, $routeParams, $filter) {
$scope.name = 'Test';
$scope.getData = function(){
$http.get('posts.json')
.then(function(res){
$scope.posts = res.data.posts;
$scope.currentPost = $filter('filter')($scope.posts, {id: $routeParams.id});
$scope.currentPost = $scope.currentPost[0]; // $filter apparently returns an array...
});
};
// setInterval($scope.getData, 1000); // DO WE REALLY NEED IT?
$scope.getData();
});
Alternative solution using _ (underscore) findWhere method:
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
app.controller('MainCtrl', function($scope, $http, $route, $routeParams, $filter) {
$scope.name = 'Test';
$scope.getData = function(){
$http.get('posts.json')
.then(function(res){
$scope.posts = res.data.posts;
// id: integer
// $routeParams.id: string
// when comparing integer to string _.findWhere was failing
// always good practice to pass radix to parseInt: http://davidwalsh.name/parseint-radix
$scope.currentPost = _.findWhere($scope.posts, {id: parseInt($routeParams.id, 10)});
});
};
// setInterval($scope.getData, 1000); // DO WE REALLY NEED IT?
$scope.getData();
});
Plnkr: http://plnkr.co/edit/N7UeaOuoNIoQgzQfrkY3?p=preview
In my code I usually use _ but now I've learnt something new - I can use $filter too!

Related

Storing list of values from HTTP GET in AngularJS?

I am getting a list by calling the $resource URL from the controller, which is viewable in the logs.
Controller
function ClubDetailController($scope, $rootScope, $stateParams, $resource,
DataUtils, entity, Club) {
var vm = this;
vm.club = entity;
vm.byteSize = DataUtils.byteSize;
vm.openFile = DataUtils.openFile;
var Todo = $resource('api/club-inchargesByClubId/:clubId');
var clubIncharges = [];
vm.clubIncharges = Todo.get({clubId: $stateParams.id}).$promise;
clubIncharges = angular.fromJson(vm.clubIncharges);
alert(clubIncharges);
})();
The problem is this list can't be stored in a var or object to be used later, for example this HTML:
<tr ng-repeat="clubIncharges in vm.clubIncharges track by clubIncharges.id">
I have also tried:
var clubIncharges = [];
clubIncharges = angular.fromJson(vm.clubIncharges);
And still couldn't get the expected output.
Updated code
var clubIncharges = [];
$http.get('api/club-
inchargesByClubId/'+$stateParams.id).then(function(response){
alert(response.data);
vm.clubIncharge = response.data;
clubIncharges = angular.fromJson(vm.clubIncharge);
vm.clubIncharges = clubIncharges;
alert(clubIncharges);
console.dir(clubIncharges);
}).catch(function(error){
console.error("Something went wrong!: " + error);
});
The list from the DB logged:
2016-10-15 13:41:22.985 DEBUG 3392 --- [nio-8081-exec-6] c.c.campuzz.aop.logging .LoggingAspect : Exit: com.campuz360.campuzz.web.rest.ClubInchargesResource.g
etClubInchargesByClubId() with result = [ClubIncharges{id=1, designaion='Chairma n', addedBy='null', clubId='2'}, ClubIncharges{id=2, designaion='bkujasrv', adde dBy='gawerg', clubId='2'}]
Latest edit
$http.get('api/club-inchargesByClubId/' + $stateParams.id).then(function (response) {
$scope.club = response.data;
}).catch(function (error) {
console.error("Something went wrong!: " + error);
});
I would do it with $http, it is cleaner to me
function ClubDetailController($scope, $rootScope, $stateParams, $http,
DataUtils, entity, Club) {
var vm = this;
vm.club = entity;
vm.byteSize = DataUtils.byteSize;
vm.openFile = DataUtils.openFile;
$http.get('api/club-inchargesByClubId/'+$stateParams.id).then(function(response){
vm.clubIncharges = response.data;
console.dir(vm.clubIncharges);
clubIncharges = angular.fromJson(vm.clubIncharges);
console.dir(clubIncharges);
}).catch(function(error){
console.error("Something went wrong!: " + error);
});
})();
EDIT
The JSON response from the OP's API has an incorrect format. I recommend to use this tool to check for a correct JSON format: https://jsonformatter.curiousconcept.com/
Todo.get({clubId: $stateParams.id}).$promise;
is returning you promise not data.
You can refer to https://docs.angularjs.org/api/ngResource/service/$resource
vm.clubIncharges = Todo.get({clubId: $stateParams.id});
Above line should work but it will not return data immediatly so your alert won't work. You can call get method like shown below to notify yourself when data is available.
vm.clubIncharges = Todo.get({clubId: $stateParams.id}, function() {
console.log(vm.clubIncharges);
});
and html should be
<tr ng-repeat="clubIncharge in clubIncharges track by clubIncharge.id">

how to unit test an angular.js service call using jasmine.js

It is a bit difficult for me to figure out the examples since I am a beginner could someone please help.
This is my code simple anjular.js service call
var app = angular.module('myApp', []);
var mycontroller = app.controller('Myctrl', function($scope, $http) {
$http.get("service.json")/*the json that i pass*/
.success(function(response) {$scope.names = response.records;});
});
I want to test this code using jasmine. What is the procedure and the code to do it.
You can use httpBackend mock service that will help to test your service.
Example-
describe('Myctrl', function() {
var $httpBackend, scope, createController, authRequestHandler;
// Set up the module
beforeEach(module('MyApp'));
beforeEach(inject(function($injector) {
// Set up the mock http service responses
$httpBackend = $injector.get('$httpBackend');
// backend definition common for all tests
authRequestHandler = $httpBackend.when('GET', 'service.json')
.respond(true);
// Get hold of a scope (i.e. the root scope)
$rootScope = $injector.get('$rootScope');
// The $controller service is used to create instances of controllers
var $controller = $injector.get('$controller');
createController = function() {
return $controller('MyController', {'$scope' : scope});
};
})
);
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch authentication token', function() {
$httpBackend.expectGET('service.json');
var controller = createController();
expect(scope.names).toBe(true);
$httpBackend.flush();
});
});

give random order to $http json oject through angular JS controller

I pull in a JSON object with my controller below, but how do I make the order random, on each page refresh?
app.controller('MainCtrl', ['$scope', '$http', 'makeRandom', function ($scope, $http, makeRandom) {
$http.get('projects/projects.json').success(function(data) {
$scope.works = data;
});
makeRandom.forEach($scope.works, function(work) {
work.rank = Math.random();
});
}]);
template.html
<section ng-repeat="work in works | orderBy:'rank'" class="showcase {{work.class}}">
...
</section>
You pretty much have all the work done, you just need to put it together:
This is based off your work:
app.controller('myCtrl', ['$scope', '$http', function($scope, $http){
$http.get('projects/projects.json').success(function(data) {
$scope.works = data;
}).error(function(){
// works on error response because I don't have your code, just copy this to success response
// here I just generate a list of ids and then randomize them
var works = [];
for(var i=0; i< 20; i++){
works.push({id: i});
}
$scope.works = makeRandom(works);
});
function makeRandom(inputArray){
angular.forEach(inputArray, function(value){
value.rank = Math.random();
});
return inputArray;
}
}]);
HTML:
<section ng-repeat="work in works | orderBy:'rank'" class="showcase {{work.class}}">
{{work.rank}} {{work}}
</section>
Here is a working example: http://plnkr.co/edit/xIwD0zWdodnYSIupm1va?p=preview

How to load a JSON data Object from other domain (no callback function) with AngularJS

Is it possible to load JSON data without callback function in AngularJS? If I manually download the json file and change the url to 'phones/phones.json'. In jQuery it is possible http://www.sitepoint.com/jsonp-examples/
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('https://raw.githubusercontent.com/angular/angular-phonecat/master/app/phones/phones.json').success(function(data) {
$scope.phones = data.splice(0, 5);
});
$scope.orderProp = 'age';
}]);
SOLVED: Thanks! I changed "raw.githubusercontent.com/angular/angular-phonecat/master/app/phones/phones.json" to "rawgit.com/angular/angular-phonecat/master/app/phones/phones.json"
See https://rawgit.com/faq
It was server side problem as Words Like Jared said.
The problem is not with your client but with your server.
http://plnkr.co/edit/a7K79KTae3CPPZx7XMfH?p=preview
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
}]);
That's virtually the same code pointed to a different URL and it works.
I think you need the HTTP request's response to contain the "Access-Control-Allow-Origin" header with a value of say "*" to access the content from another site. How to do that will vary depending on your server technology.

Making 'Add new user', JSON data overwrites the current data..needs to be added.--AngularJS

I am new to AngularJS. While trying to send formdata to Json file after click 'Add New Member' button, the new Json data overwrites the current existing Json data. I need the data to be added after the last data.
I used the code below
var memberControllers = angular.module('memberControllers', []);`memberControllers.controller('addListCtrl', ['$scope', '$http', '$location',
function($scope, $http, $location){
$scope.members = [];
$scope.formData = {};
$scope.addMember = function(){
$http.post('data/members.json', $scope.formData).
success(function(data){
console.log('added ' + data);
$scope.formData = {};
$scope.members = data;
$scope.members.push(data);
})
.error(function(data){
console.log('Error: ' + data);
});
$location.path('/members');
/*});*/
};
}]);`
The result shows from Json file --->
{"id":"1","name":"Jane" }
I expect below --->
[{"id":"1","name":"Jane"},{"id":"2","name":"John"},{"id":"3","name":"Tom"}]
$scope.members = data; overwrites members - omit this line and just use push as you're doing right after.