I have an angular application which I need to call web services. I have to call two different url to get data.
In my first url is like ==>
abc.com/student/3 this is the list of student. and another URL is
abc.com/parent/idofStudent3 when I pass student id of 3 in the second URL I need to get parent first name from the second URL.
I am able to retrieve the first URL data but I am unable to retrieve second URL data by passing first record data in ng-repeat. Could you please help me how to retrieve parent name in the web page?
Html Page
<h1 ng-repeat="x in myWelcome">
{{x.firstname}} || {{x.parentId}} </h1>
Here instead of displaying parentid I need to call another web service to display parent name by passing parentId as a parameter. how to call another web service here?
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("abc.com/student/3")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
==> First webservice response is like :
{
"student":[
{
"name":"john",
"parentId": 12,
"address":"NYC"
},
{
"name":"Rohi",
"parentId": 14,
"address":"NJ"
},
]
}
==> second webservice response is like this when parentID=12:
{
"firstName": "Sr. John",
}
======> when parentIS 14
{
"firstName": "Sr. Rohi",
}
-------------------------
firstname || parentName
-------------------------
John || Sr. John
Rohi || Sr. Rohi
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.myWelcome = []
$http.get("abc.com/student/3")
.then(function(response) {
$scope.StudentData = response.data;
if($scope.StudentData){
$scope.myWelcome.push($scope.StudentData)
$http.get("abc.com/parent/$scope.StudentData.studentId")
.then(function(response) {
$scope.parentData = response.data;
$scope.myWelcome.push($scope.parentData)
});
}
});
});
</script>
I guess this might help you
Currently, you are searching for Parent details in the wrong scope object; myWelcome object is containing data from first service call, which returned list of student details only.
You can define a new scope object and bind data to it from second service call which will contain parent details; you can then use that object in ng-repeat.
Related
In my angular application I store the logged in user name in a cookie.
And I want to display this user name in the web page header.
I can retrieve this in my controller as below and display in the page.
$rootScope.fullName = $cookies.get('user');
But instead of doing this in every controller, is it possible to do it in one place and always get this data ?
Update #1:
I don't use ui-view. I use angular route and a sample is as below.
Are there any simple approach please ?
var mdmApp = angular.module('mdmApp');
// Routes
mdmApp.config(function($routeProvider, $httpProvider, $locationProvider) {
$routeProvider
.when('/listScopeAndFrequency/:reportTypeId', {
templateUrl : '3_calendar/listScopeAndFrequencies.html',
controller : "listScopeAndFrequenciesController"
})
.when('/listTemplateFrequencyExceptions/:reportTypeId/:consolidationScopeCode/:frequencyCode', {
templateUrl : '3_calendar/listTemplateFrequencyExceptions.html',
controller : "listTemplateFrequencyExceptionsController"
})
.when('/viewSubmissionDates', {
templateUrl : '3_calendar/viewSubmissionDates.html',
controller : "viewSubmissionDatesController"
})
Update #2
I tried like below but could not get any dynamic values from REST API, I am only able to hard code the value. Not able to read from cookie, localStorage or var all are undefined or give errors.
mdmApp.factory('userService', function($http, $localStorage, $cookies) {
var fullName ;
// Gets user details
$http.get("/mdm/getUser")
.success(function(data, status, headers, config) {
console.log('userService > user : ' +data.fullName);
fullName = data.fullName;
$localStorage.user = data;
$cookies.put('user', data.fullName);
})
.error(function(data, status, headers, config, statusText) {
console.log("Error while retrieving user details.");
});
console.log('fullName : ' +fullName);
console.log('$cookies.get(user) : ' +$cookies.get('user'));
console.log('$localStorage.user : ' +$localStorage.user);
return { name: "hard code only works here"};
});
mdmApp.directive('userTitle', ['userService', function(user) {
console.log('userTitle > user : ' +user);
return {
template: user.name,
};
}]);
Why don't you use a service? Those are specially designed for this task:
Angular services are:
Lazily instantiated – Angular only instantiates a service when an application component depends on it.
Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
How I do it (not necessarily the best way):
setup an independent angular app (non-secured area) for user registration, on login store a token or some identifier in a cookie or the localStorage
when instantiating the full angular app (secured area), create a service which will get back the previous value and inject it whenever you need the user
My User service looks like:
angular.module('app.core')
.service('User', User);
function User($rootScope, localStorageService) {
let user = localStorageService.get('user');
let token = localStorageService.get('userToken');
if(!token) {
//this loads another angular app which has nothing to do with this secured area (on /login)
window.location = '/login'
return;
}
for(let i in user)
this[i] = user[i]
this.token = 'Bearer ' + token;
//note you could reference this to the rootScope so that every scope can have the User object, this can be considered as bad practice!
//$rootScope.user = this;
return this;
}
I would go with a service and a directory for this.
As soyuka explained. Services exists for the purpose of sharing data between parts of an application. I would then use a directive to handle the data in relation to the DOM, that is, to write to the header.
Service/factory:
app.factory('userService', function() {
// do what you have to get your user and save the data.
return { name: 'John'};
});
Directive. Notice the injection of the service. This could be done through a controller if you wish. It depends on whether you want your directives to have a dependency to the service.
app.directive('userTitle', ['userService', function(user) {
// do what you want with the data
return {
template: user.name,
};
}]);
Here the service just returns a dummy name and the directive outputs the name in the DOM.
Here is a running plunker of the setup.
When I run the following Firebase query:
var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status');
data = $firebaseObject(ref);
console.dir(data);
I get the following object:
d
$$conf: Object
$id: "status"
$priority: null
Active, not recruiting: 39
Approved for marketing: 1
Completed: 339
Enrolling by invitation: 10
Not yet recruiting: 23
Recruiting: 128
Suspended: 3
Terminated: 38
Unknown: 74
Withdrawn: 15
__proto__: Object
I am trying to access the "Completed" element with value 339. However, console.log(data['Completed']) returns undefined. What is wrong?
A $firebaseObject starts out as an empty object, but when the data has been downloaded from the Firebase database, it then populates the object.
At first, you don't see anything because the data hasn't downloaded yet. Your console.log() runs a nanosecond after the $firebaseObject is created. The data is downloaded milliseconds after.
So you're probably asking, How do I handle the data if it doesn't exist at first?
What you can do is attach the $firebaseObject to $scope. And then bind it in your template. When the data downloads the Angular $digest loop runs, and refreshes your template.
Your controller would look like this:
app.controller('MyCtrl', function($scope, $firebaseObject) {
var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status');
$scope.data = $firebaseObject(ref);
});
Your template would look like this:
<div>Did you do it? {{ data.Completed }}</div>
There is another way, which takes a bit more setup, but it's my personal favorite. You can also use the router to resolve the data into the controller.
angular.module('app', ['firebase'])
.constant('FirebaseUrl', '<my-firebase-app>')
.service('rootRef', ['FirebaseUrl', Firebase])
.controller('MyCtrl', MyController)
.config(ApplicationConfig);
function ApplicationConfig($routeProvider) {
$routeProvider.when('/', {
controller: 'MyCtrl',
template: 'view.html',
resolve: {
data: function ($firebaseObject, rootRef) {
var ref = rootRef.child('companies/endo/status');
// a promise for the downloaded data
return $firebaseObject(ref).$loaded();
}
}
});
}
function MyController($scope, data) {
$scope.data = data;
console.log(data.Completed); // will work because the data is downloaded
}
I have a service which I would like to use across multiple controllers. The services is defined like this:
app.factory('Data', ['$http',
function($http) {
var Data = this;
var theProduct = {};
return {
product: function() {
return theProduct;
},
getProduct: function(ext_id) {
return $http.post('get_product', {
product_id: ext_id
}).success(function(data) {
theProduct = data;
});
}
}
}
]);
I have a form, that uses the ProductFormController to retrieve product data when it's submitted. That controller looks like this:
app.controller('ProductFormController', ['$scope', '$http', 'Data',
function($scope, $http, Data) {
/*
* Get a product and all of it's data from the server
*/
$scope.getProduct = function() {
Data.getProduct($scope.extProductId).success(function(data) {
console.log(data);
});
}
}
]);
Then, I have an AppController, which should display certain sections when a product object exists in the Data service.
<div class="row" id="productInfo" ng-show="product().id" ng-controller="AppController">/div>
Within AppController, I have this line:
$scope.product = Data.product;
I would like the productInfo div to show whenever a product object exists in the Data service, but it seems that the variable never gets updated. I've seen this question, but do not believe the accepted answer actually answers the question:
Angular: share asynchronous service data between controllers
I'm new in AngularJS, and JS overall. But I think it's fairly simple coming from Java in school.
My first service contained this:
app.factory('User', function($http) {
var user = {
username : null,
company : null,
address : null,
city: null,
country: null
};
$http.get('/webservice/user').success(function(data){
user.username = data.username;
user.company = data.company;
user.address = data.address;
user.city = data.city;
user.country = data.country;
})
return user;
})
I accessed it from the UserCtrl:
app.controller('UserCtrl', ['$scope', 'User', function ($scope, User){
$scope.user = User;
}]);
And in the index.html I simply called:
{{user.username}} {{user.company}} ...
And so forth.
Now I have an array of objects, I use this method:
app.factory('Cards', function($http) {
var cards = [{id:null, name: null, info: null}];
$http.get('/webservice/cards').success(function(data){
for(var i=0;i<data.length;i++){
cards[i] = data[i];
}
})
return cards;
})
The controller looks the same.
app.controller('SearchCtrl', ['$scope', 'Cards', function ($scope, Cards){
$scope.cards = Cards;
}]);
And I access them with a
<li ng-repeat="card in cards">
{{card.id}} {{card.info}}</li>
My question is, do I really have to have a for loop in the $http.get() method?
No Need for the loop, angular js ng-repeat itself works as an foreach loop.
// Js Code
app.factory('Cards', function($http) {
$scope.cards = [];
$http.get('/webservice/cards').success(function(data){
$scope.cards = data;
}
return $scope.cards;
})
//html
<li ng-repeat="card in cards">
{{card.id}} {{card.info}}</li>
I solved this by using ngResource.
When doing using RESTful APIs this is the way to do it. Instead of using the $http.get() method, I simply used
app.factory('CardService', ['$resource', function($resource) {
return $resource('/webservice/cards',{});
}]);
Using $scope inside of a service is not recommended, that way you have lost the functionality of the service.
In the controller, I then used:
app.controller("CardCtrl", ['$scope', 'CardService', function($scope, CardService){
$scope.cards = CardService.query();
})
Using the other ways caused conflict in the 2-way-binding. First it launched the controller, then checked the service, then the controller, then the service again. When working with an object, this worked great. Working with an array, this way is better.
I'm trying to create a simple blog website using AngularJS. I'm just starting out, so what I'm thinking my not be the best way to do this, so any alternative suggestions are welcome.
I have a controller.js file with two blog controllers. One to display a list of blog posts, and the other that displays the post content by including an HTML file.
controller.js
myAppControllers.controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('articles/articles.json').success(function (articles) {
$scope.articles = articles;
});
}]);
myAppControllers.controller('BlogPostCtrl', ['$scope', '$routeParams', function ($scope, $routeParams) {
$scope.includeFile = 'articles/' + $routeParams.blogPostId + '.html';
}]);
articles.json
[
{
"id": "test-article-one",
"title": "Test Article one",
"author": "Gareth Lewis",
"datePosted": "2015-06-23",
"summary": "This is a test summary"
},
{
"id": "test-article-two",
"title": "Test article two",
"author": "Gareth Lewis",
"datePosted": "2015-06-23",
"summary": "This is a test for article two"
}
]
app.js
when('/blog', {
templateUrl: 'partials/blog-articles.html',
controller: 'BlogListCtrl'
}).
when('/blog/:blogPostId', {
templateUrl: 'partials/blog-post.html',
controller: 'BlogPostCtrl'
}).
blog-post.html
<ng-include src="'partials/header.html'"></ng-include>
<!-- Want to add title, author, datePosted information here... -->
<article class="content">
<ng-include src="includeFile"></ng-include>
</article>
This blog listings work fine. When I click into a blog post, it also serves up the content from the HTML file OK as well. However, I want to be able to reuse the title, author and datePosted properties from the selected article in the blog-post.html partial view. What's the best way to do this? Would I need to pass them to the Controller somehow to then pass to the view? I don't really want to pass these as routeParams. Or would I need to do a $http.get on articles.json and iterate through to find the selected article and then pass the property values back to the view?
Thanks for the help.
You said that suggestions are welcome, so here it goes.
1 - Transport all your Blog logic to a service;
2 - Provide the data on resolving routes. This is a better approach to handle errors during the load time, 404s, and so on. You can provide a listener to $routeChangeError and deal with it there;
3 - On the service declared below, you have the methods to call your data and a method to retrieve the list cached on the service:
// services.js
myAppServices
.service('BlogService', ['$http', '$q', function ($http, $q) {
var api = {},
currentData = {
list: [],
article: {}
};
api.getSaved = function () {
return currentData;
};
api.listArticles = function () {
var deferred = $q.defer(),
backup = angular.copy(currentData.list);
$http.get('articles/articles.json')
.then(function (response) {
currentData.list = response;
deferred.resolve(response);
}, function () {
currentData.list = backup;
deferred.reject(reason);
});
return deferred.promise;
};
api.getArticle = function (id) {
var deferred = $q.defer(),
backup = angular.copy(currentData.article),
path = 'articles/' + id + '.html';
$http.get(path, {
cache: true
})
.then(function (response) {
currentData.article = {
path: path,
response: response
};
deferred.resolve(currentData.article);
}, function (reason) {
currentData.article = backup;
deferred.reject(currentData.article);
});
return deferred.promise;
};
return api;
}]);
The BlogService.getSaved() will retrieve the stored data, made after each call.
I've made a method to call the ng-include path too, so you can verify if it exists, with cache === true, the browser will keep a copy of it, when calling it again on the view. A copy of the response of the blog article is made too, so you can access its path and the response whenever you need.
On the controllers below, they were adaptated to supply the current needs:
// controller.js
myAppControllers
.controller('BlogListCtrl', ['$scope', 'articles',
function ($scope, articles) {
$scope.articles = articles;
/* OTHER STUFF HERE */
}
])
.controller('BlogPostCtrl', ['$routeParams', '$scope', 'article' 'BlogService',
function ($routeParams, $scope, article, BlogService) {
// On `article` dependency, you have both the original response
// and the path formed. If you want to use any of it.
$scope.includeFile = article.path;
// To get the current stored data (if any):
$scope.articles = BlogService.getSaved().list;
// Traverse the array to get your current article:
$scope.article = $scope.articles.filter(function (item) {
return item.id === $routeParams.id;
});
/* OTHER STUFF HERE */
}
]);
And the route declarations were changed to load the data when resolving the routes.
// app.js
$routeProvider
.when('/blog', {
templateUrl: 'partials/blog-articles.html',
controller: 'BlogListCtrl',
resolve: {
articles: ['BlogService', '$routeParams', function (BlogService, $routeParams) {
return BlogService.listArticles();
}]
}
})
.when('/blog/:id', {
templateUrl: 'partials/blog-post.html',
controller: 'BlogPostCtrl',
resolve: {
article: ['BlogService', '$routeParams', function (BlogService, $routeParams) {
return BlogService.getArticle($routeParams.blogPostId);
}]
}
})
This is maybe a common question in angular. What you have to understand is that Scope is defined per controller... In order to share data across controller you still have the option to use $scope.$parent or $rootScope to link controllers but I would use those carefully.
It is better to use Angular Services which are based on singleton patterns therefore you can use them to share information between controllers and I think it will be a better approach.
I found that this has been previously discussed and here are some good examples:
AngularJS Service Passing Data Between Controllers
You can use a global scope to set this data, or you can use service to communicate between the controllers. There is a lot of ways to resolve this problem read a little bit more about services in the link bellow and see if you can find how to resolve your problem.
AngularJS: Service vs provider vs factory