Load first json object by default - Angular - angularjs

I'm hoping this is an easy question to answer...
I'm trying to create a table that loads my json, then be able to click a row and load more details that pertain to the json object. When you click a row it should load additional details at the top of the page. The row clicking part is working fine. What I'm having trouble with is loading the initial object by default.
Below is an example of what I'm referring to:
var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
console.log(data);
});
$scope.select = function (item) {
$scope.selected = item;
}
}]);
http://embed.plnkr.co/6LfAsaamCPPbe7JNdww1/
I tried adding this after $scope.select, but got an error:
$scope.selected = item[0];
How do I get the first object in my json to load by default?
thanks in advance

Inside your promise resolve function assign the first item of the array, as a selected value:
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log(data);
});

var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log($scope.itemDetails);
console.log($scope.selected);
});
}]);

Related

Angular Js : undefined value in pop up

I get a problem in AngularJS when getting data from JSON using service factory ($resource)
services.factory('GetCustomerByEmailFactory', function ($resource) {
return $resource(url + '/customerService/getCustomerByMail?email=:email', {}, {
getByMail: { method: 'GET', params: {email: '#email'} }
});
});
this service works well
but the controller part doesn't work
app.controller('CustomerCreationCtrl', ['$scope','PostCustomerFactory', '$location','Subscription','AddNotificationFactory','$routeParams','GetCustomerByEmailFactory',
function ($scope, PostCustomerFactory, $location,Subscription,AddNotificationFactory,$routeParams,GetCustomerByEmailFactory) {
$scope.customer ={};
$scope.not ={};
$scope.aftercustomer ={};
$scope.createNewCustomer = function(){
Number($scope.customer.PhoneNumber);
$scope.customer.SubscriptionDate = "1990-02-23T00:00:00";
$scope.customer.ManagerIdCustomer=1;
PostCustomerFactory.create($scope.customer);
var customer = GetCustomerByEmailFactory.getByMail({email:$scope.customer.Email}).$promise;
customer.then(function (responce){
$scope.aftercustomer = responce;
window.alert($scope.aftercustomer.Id);
$scope.not.CustomerId = $scope.aftercustomer.Id;
$scope.not.ManagerId = $routeParams.id;
AddNotificationFactory.create($scope.not);
});
$location.path("/login");
};
}]);
the window.alert show me an undefined value so that it doesn't get the data

Why not available $scope.value of the variable in runtime?

Why not available $scope.reserved of the variable in runtime? In template {{reserved}} is ок, but in controller value = undefibed.
I have the following code
Service:
'use sctict'
angular.module('starter.services', [])
.service('api', ['$http', '$q', function api($http, $q) {
var server = 'http://localhost/ires-api';
var jsondata = {
getReservedHours: function (masters, date) {
var deferred = $q.defer();
var promise = $http({ method: 'GET', url: server + '/reservations/' + masters + '/' + date, cache:true})
.success(function(response) {
//return response;
deferred.resolve({
data: response
});
}).error(function(msg, code) {
deferred.reject(msg);
$log.error(msg, code);
});
return deferred.promise;
},
}
return jsondata;
}]);
Controller
$scope.click = function(){
masters = [5,51];
api.getReservedHours(masters, '2007/08/27').then(function(response) {
$scope.reserved = response.data;
});
console.log($scope.reserved); // undefined ....
}
I think you're missing the assignment?
api.getReservedHours(masters, '2007/08/27').then(function(response) {
$scope.reserved = response.data;
});
Because "getReservedHours" is an asynchronous request and $scope.reserved is undefined (because the request is not complete) when you print it. Use this code instead
$scope.click = function(){
masters = [5,51];
api.getReservedHours(masters, '2007/08/27').then(function(response) {
$scope.reserved = response.data;
console.log($scope.reserved); // This would work
});
console.log($scope.reserved); // undefined ....
}

load jsonp into multiple AngularJS controllers

I have a jsonp call to a server which returns an object containing two objects.
At the moment I make the jsonp call with jQuery because I've just started learning AngularJS and I dont know how it's done.
I want to use data.filters in navController and data.results in contentController
What would be the correct way to achieve this with AngularJS ?
(function($, angular) {
$(function() {
$.ajax({
jsonp: "JSONPCallback",
url: 'myUrl',
dataType: 'jsonp',
success: function(data) {
//data = {"filters":{...},"results":{...}}
}
});
});
var app = angular.module('app', []);
var controllers = {};
controllers.navController = function($scope) {
$scope.filters = [{}];
};
controllers.contentController = function($scope) {
$scope.results = [{}];
};
app.controller(controllers);
})(jQuery, angular);
Hi please see here http://plnkr.co/edit/hYkkQ6WctjhYs8w7I8sT?p=preview
var app = angular.module('plunker', []);
app.service('dataService', function($http){
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
var dataReady= false
var filters = [];
var results = [];
function getData() {
if (dataReady)
retrun
else
{
$http.jsonp(url)
.success(function(data){
//in your case
//angular.copy(data.filters, filters)
//angular.copy(data.results , results )
angular.copy(data.posts[0], results);
angular.copy(data.posts[1], filters);
dataReady = true
}).error(function(){
alert('cant load data');
});
}
}
return {
filters : filters,
results : results,
getData : getData
}
})
app.controller('MainCtrl', function($scope,dataService) {
$scope.name = 'World';
$scope.items = dataService.results;
dataService.getData();
});
app.controller('SecondCtrl', function($scope,dataService) {
$scope.filters = dataService.filters;
dataService.getData();
});

AngularJS binding service variable to controller

I am a Angular noob and having problems with binding a variable from one of my services to one of my controllers. I have read at least a dozen posts on the subject and nothing seems to be working for me.
Here is the controller:
app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
$scope.teamService = teamService;
$scope.selectedTeam = null;
$scope.selectTeam = function(teamId){
$scope.selectedTeam = teamService.getTeam(teamId, $scope.login.loginId);
};
}]);
Here is the service:
angular.module('teamService', [])
.service('teamService', function($http, $q){
this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
this.userTeams = [];
this.getTeam = function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
var promise = $http({
url: "/url-for-getting-team",
method: "POST",
data: postData
});
promise.success(function (data) {
if (data.status === "success") {
this.selectedTeam = data.response;
return data.response;
}
});
promise.error(function () { //TODO handle getTeam errors
return {};
});
};
this.getSelectedTeam = function(){
return this.selectedTeam;
};
});
And here is the template:
<div class="jumbotron main-jumbo" ng-controller="TeamController">
<h1>{{selectedTeam.teamName}}</h1>
</div>
I have tried binding to the getSelectedTeam function and the service variable itself. Do I need to set up a $watch function in the controller? Any assistance would be greatly appreciated.
EDIT:
I tried turning my service into a factory, which still did not help me, so then I looked at a provider that was properly working that I had already written in the application. I converted my "teamService" into a provider and finally worked like a charm. Thanks for the contributions guys.
Code from my new provider:
angular.module('teamService', [])
.provider('teamService', function () {
var errorState = 'error',
logoutState = 'home';
this.$get = function ($rootScope, $http, $q, $state) {
/**
* Low-level, private functions.
*/
/**
* High level, public methods
*/
var wrappedService = {
/**
* Public properties
*/
selectedTeam: {teamName:"Select a team"},
userTeams : null,
createTeam: function(loginId, name, description, locationName, managed){
var postData = {loginId:loginId, teamName:name, teamDescription:description, teamLocationName:locationName, teamManaged:managed};
var promise = $http({
url: "/create-team-url",
method: "POST",
data: postData
});
return promise;
},
getTeam: function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
var promise = $http({
url: "/get-team-url",
method: "POST",
data: postData
});
promise.success(function (data) {
if (data.status === "success") {
wrappedService.selectedTeam = data.response;
}
});
promise.error(function () { //TODO handle getTeam errors
wrappedService.selectedTeam = {};
});
},
getUserTeams: function(loginId) {
var postData = {loginId: loginId};
var promise = $http({
url: "/team-list-url",
method: "POST",
data: postData
});
return promise;
},
joinTeam: function(teamId, loginId){
var postData = {teamId:teamId, loginId:loginId};
var promise =$http({
url: "/join-team-url",
method: "POST",
data: postData
});
return promise;
},
getSelectedTeam: function(){
return wrappedService.selectedTeam;
}
};
return wrappedService;
};
});
As seen in my edit. I converted my service into a provider and all the changes seem to propagate to the view with no issues. I need to further analyze the difference between the factory, service, and provider in order to gain a higher understanding of what is going on here.
The main issue with the code is the way that promises are used. You can either correct that within the service, or handle it in the controller. As an example of the latter, you can re-write the above as:
Controller Code:
app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
$scope.teamService = teamService;
$scope.selectedTeam = null;
$scope.selectTeam = function(teamId){
teamService.getTeam(teamId, $scope.login.loginId).then(
function(result){
$scope.selectedTeam = result.data;
},
function(error){
console.log(error);
}
)
};
}]);
Service code:
angular.module('teamService', [])
.service('teamService', function($http, $q){
this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
this.userTeams = [];
this.getTeam = function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
return $http({
url: "/url-for-getting-team",
method: "POST",
data: postData
});
};
this.getSelectedTeam = function(){
return this.selectedTeam;
};
});
You can also handle this in the service itself, but it requires a little more code. The key thing is that the getTeam call is asynchronous and needs to be handled using proper promise constructs.

After I call a service my view does not get updated in AngularJS

I have the following service:
angular.module('adminApp')
.factory('subjectService', function ($http) {
return {
get: function (testAccountId) {
return $http({
method: 'GET',
url: '/api/Subjects/GetSelect',
params: { testAccountId: testAccountId }
});
}
}
});
The following code works when I call http directly but now when I use the service:
$scope.$watch('selectedTestAccount', function () {
if ($scope.selectedTestAccount != null) {
$scope.myData = null;
$http({
method: 'GET',
url: '/api/Subjects/GetSelect',
params: { testAccountId: $scope.selectedTestAccount }
}).success(function (result) {
$scope.subjects = result;
$scope.myData = null;
});
//subjectService.get($scope.selectedTestAccount)
// .then(function (result) {
// $scope.subjects = result;
// $scope.myData = null;
// alert($scope.subjects);
// }, function (result) {
// alert("Error: No data returned");
// });
}
});
Related to this question. Is this the correct way to call the service. I saw another suggestion that looked like the following and used promises. Should I be doing this:
services.factory('MultiRecipeLoader', ['Recipe', '$q',
function(Recipe, $q) {
return function() {
var delay = $q.defer();
Recipe.query(function(recipes) {
delay.resolve(recipes);
}, function() {
delay.reject('Unable to fetch recipes');
});
return delay.promise;
};
}]);
I tried to reproduce your exemple in a plunker. Let me know if it is what you are look for:
http://plnkr.co/edit/6s5utccjgHTnrrokM1u8?p=preview
In this demo, there is a dropdown that changes the value of the account variable that is $watched in the controller. If the account value changes, it calls the SubjectsServices and updates the unordered list with the names of the subjects. As an addition, there is also a dropdown filled with the same values.
If the only way to change the value is through the dropdown, maybe you can only use the ng-change directive on the select to call an update function that will do the same work.
$scope.update = function() {
SubjectService.get($scope.account).then(function(result) {
$scope.subjects = result.data;
}, function(result) {
// error handling...
});
};
<select ng-change="update()"></select>
The object received in parameter from the method then on an $http promise has a data property containing the requested data.
$http.get(...).then(function(result) {
var subjects = result.data;
});

Resources