I am getting a response from http get request and Iam using the response to iterate in the data
<div id="container" ng-app="myApp" ng-controller="myctrl">
<div ng-repeat="profile in profiles">
<p>{{profile.username}}</p>
</div>
</div>
This is for adding one profile on click
<input ng-click="addProfile()" type="button" value="add Profile" />
Here is my get request in the controller
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope, $http) {
$scope.profiles = [];
$http.get("test1.json")
.then(function(response) {
$scope.profiles = response.data.profiles; //Response is provided below
});
$scope.addProfile = function(){
$http.get('test2.json')
.then(function(response) {
alert("af");
$scope.items = response.data.profiles; //Response is provided below
$scope.profiles.push($scope.items);
console.log($scope.profiles); //gives the update Array
});
});
});
response of my get request of test1.json
{
"Id": "44442232",
"profiles": [
{
"type": "Friend",
"username": "Username 1",
},
{
"type": "Student ",
"username": "Username 2",
}
]
}
response of my get request of test2.json
{
"Id": "44442232",
"profiles": [
{
"type": "Friend",
"username": "Username 4",
},
{
"type": "Student ",
"username": "Username 5"
}
]
}
I have tried console.log after updating in the array.The array is updated but the div in ng-repeat is not getting updated?
Please close your JSON calling request by putting ')' at the end. There is no error apart from this and the same code works for me fine.
// Code goes here
var myApp = angular.module("myApp", []);
myApp.controller("myctrl", function($scope, $http) {
$http.get('test1.json')
.then(function(response) {
$scope.profiles = response.data.profiles; //Response is provided below
});
$scope.addProfile = function(){
$http.get('test2.json')
.then(function(response) {
$scope.items = response.data.profiles; //Response is provided below
angular.forEach($scope.items, function(value) {
$scope.profiles.push(value);
});
console.log($scope.profiles);
});
};
});
Please find this updated js code and check. Once it is fixed let me know. happy coding :)
First of all I don't think you need $scope.$apply() to trigger the digest cycle. You are in angular context.
Second, you are missing a ')' when you are calling .then(). You currently have '.then(function(){};'
Third, your response object should not have a comma after the username property if that property is the last one in the object.
Also do you have a silent fail, or it is an error in the console, and the processed html for the ng-repeat is blank or you get the angular interpolation syntax {{profile.username}}?
Related
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.
I have variables in my angular controller and I'd like to take the data in the variable and put in a script tag in my html but I have no clue how to execute this. I'm doing this because I want to take a picture and put it into my LinkedIn post with the share button. Based on the docs here, it seems pretty straight forward if I can just get the data from my controller into their script tags.
For example:
controller.js
.controller('PostCtrl', function ($scope, $http, $stateParams) {
$scope.test = "something";
$scope.hope = 5
$scope.array = [things];
}
html
<script>
var payload = {
"comment": $scope.test "content": {
"title": $scope.hope,
"someArray": $scope.array,
"submitted-url": window.location.href
}
};
</script>
//////////////////////////
Thanks for the copious comments. Here is what I'm trying in more detail with LinkedIn:
<script type="IN/Share" data-url={{webAddress}} data-counter="right">
$.get( "https://public-api.wordpress.com/rest/v1.1/sites", function( response ) {
var post = _.first(_.filter(response.posts, function(n){return n.title.replace(/ /g,"-").replace(/[:]/g, "").toLowerCase() === $stateParams.id}));
var post1 = _.assign(post, {category: _.first(_.keys(post.categories)), pic: _.first(_.values(post.attachments)).URL, credit: _.first(_.values(post.attachments)).caption, linkCredit: _.first(_.values(post.attachments)).alt, fullStory: post.content.replace(/<(?!\s*\/?\s*p\b)[^>]*>/gi,'')});
**var image = post1.pic;**
**var title = post1.title;**
**var webAddress = window.location.href;**
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function shareContent(title, image, webAddress) {
var payload = {
"content": {
"title": title,
"submitted-image-url": image,
"submitted-url": webAddress
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
});
</script>
I still think something is going wrong. But what? Am I using the http correctly as I've only done it using Angular thus far.
See the snippet just below how to access Angular Scope outside angular :)
EDIT (Afer reading your updated question)
You'll better transcode all your LinkedIn scripts to angular way as kicken suggest you :) :
less spagetti code
less maintenance
more time to watch lol cats on YT !
If you still want to do that way :) ==>
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.test = 'toto';
$scope.hope = 'My Title';
$scope.array = ['A', 'B', 'C'];
$scope.payload = {};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var myFunction = function() {
var e = document.getElementById('app');
var $scope = angular.element(e).scope();
console.log($scope.payload);
$scope.payload = {
"comment": $scope.test,
"content": {
"title": $scope.hope,
"someArray": $scope.array,
"submitted-url": window.location.href
}
};
$scope.$apply();
};
</script>
<body ng-app="app" ng-controller="MainCtrl" id="app">
<p>Hello {{payload}}!</p>
<button onclick="javascript:myFunction()">Click me</button>
</body>
Rather than try and pass data from Angular into a generic <script> tag, what you need to do is move the LinkedIn code into Angular.
A quick glance at the JavascriptSDK documentation suggests that this is the key code for making the linked in request:
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
What you can do then is place that code into your angular code at whatever point you need it. You mention the data for your payload comes from a $http request so you would likely want this into your $http success handler.
$http({url:'/whatever'}).then(function(response){
var payload = { /* Generate payload */ };
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
function onSuccess(){ /* LinkedIn success */ }
function onError(){ /* LinkedIn error */ }
});
As others have suggested, moving all of your javascript code into your controller would be the best solution if possible. To do that, your controller would look something like this:
.controller('PostCtrl', function ($scope, $http, $stateParams) {
$scope.test = "something";
$scope.hope = 5
$scope.array = [things];
$scope.sendData = function () {
var data = $.param({
"comment": $scope.test,
"content": {
"title": $scope.hope,
"someArray": $scope.array,
"submitted-url": window.location.href
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('https://api.linkedin.com/v1/people/~/shares?format=json', data, config)
.success(function (data, status, headers, config) {
//it worked
})
.error(function (data, status, header, config) {
//there was an error
});
};
}
Then, in your html, you would put ng-submit="sendData()" on the form you use to share. If the share stuff isn't in a form, you could then just do ng-click="sendData()".
I am trying to access the data from my JSON file to be used within my controller for further manipulation using Angular. To start, here are the first couple entries of the file 'cards.json'
{ "TheGrandTournament": [
{
"name": "Buccaneer",
"cardSet": "The Grand Tournament",
"type": "Minion",
"rarity": "Common",
"cost": 1,
"attack": 2,
"health": 1,
"text": "Whenever you equip a weapon, give it +1 Attack.",
"collectible": true,
"playerClass": "Rogue",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_029.
},
{
"name": "Competitive Spirit",
"cardSet": "The Grand Tournament",
"type": "Spell",
"rarity": "Rare",
"cost": 1,
"text": "<b>Secret:</b> When your turn starts, give your minions +
"collectible": true,
"playerClass": "Paladin",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_073.
"mechanics": [{"name": "Secret"}]
}, ...
]}
I have had success with accessing the information from my view using this code
<div ng-controller="CardCtrl">
<button id="loadbtn" ng-click="load()">Load</button><br>
<div ng-repeat="cards in data.TheGrandTournament | limitTo:2">
<pre>{{ cards.name }}</pre>
</div>
</div
My controller looks like this:
angular.module('cards', []).controller('CardCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.method = 'GET';
$scope.url = 'cards.json';
$scope.load = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.data = response.data;
console.log("Read file", $scope.url, "successfully.");
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
};
$scope.cardData = angular.fromJson($scope.data[0]);
console.log($scope.cardData);
}]);
The error returned when trying to output $scope.cardData to a console log is
"TypeError: Cannot read property '0' of undefined".
I tried then parsing the data from the json object using angular.fromJson() but it is not working as I am intending.
You should move $scope.data into the success callback of the promise:
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.cardData = response.data.TheGrandTournament;
console.log("Read file", $scope.url, "successfully.");
console.log($scope.cardData);
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
// scope parameter data is not accessible here, as it's not yet added
//$scope.cardData = angular.fromJson($scope.data[0]);
//console.log($scope.cardData);
}]);
Replace:
$scope.data = response.data;
with:
$scope.data = response.data.TheGrandTournament;
Try to replace:
$scope.cardData = angular.fromJson($scope.data[0]);
with:
$scope.cardData = angular.fromJson($scope.data["TheGrandTournament"][0]);
I am new to AngularJS. I am trying to retrieve firstname, lastname & State from an API, using a search functionality for a statecode, say, "DC" for ex.
I have modified to be simpler, and I still see no result on the page:
Here's my get:
function ItemsController($scope, $http){
$http.get("https://my.ncarb.org/Public/api/certification/search?statecode=dc")
.success(function(data, status, headers, config){
$scope.items = data;
});
}
Here's a sample of my api:
{
"data": [
{
"id": "14e1047c-b811-40f7-8a21-780ae5edf1ed",
"firstName": "Kent",
"lastName": "Abraham",
"city": "WASHINGTON",
"stateCode": "DC",
"countryCode": "USA"
},]
}
and here's my HTML:
<body ng-controller="ItemsController">
<h1>jSON Data</h1>
<table>
<tr ng-repeat="item in items">
<td>{{item.id}}</td>
<td>{{item.firstName}}</td>
<td>{{item.stateCode}}</td>
</tr>
</table>
</body>
But my output, upon inspecting, getting a 200 OK status, but nothing gets displayed on the page...Any reason why ?
Attached - Screenshot of response in Dev tools
You are doing it wrong. $http.get returns a promise.
Here is the working sample.
HTML:
<div ng-app="app">
<div ng-controller="ItemsController">
<h1>jSON Data</h1>
<table>
<tr ng-repeat="item in items">
<td>{{item.id}}</td>
<td>{{item.firstName}}</td>
<td>{{item.stateCode}}</td>
</tr>
</table>
</div>
</div>
Angular App & Controller:
var module = angular.module('app', []);
angular.module('app').controller('ItemsController', ['$scope', '$http', function ($scope, $http) {
$http.get('https://my.ncarb.org/Public/api/certification/search?statecode=dc').then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.items = response.data.data;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}]);
Output:
data is complete response from the api.
Just do :
$http.get("https://my.ncarb.org/Public/api/certification/search?statecode=dc")
.success(function(data, status, headers, config){
$scope.items = data.data;
});
It will solve your problem :)
Why do you do a second $http.get() ? If the first one return the sample of the api it is useless because you should pass something that return a response in parameter of your $http.get()
Maybe you should make$scope.states = response.data just after the call of your API.
I'm in the process of learning a bit of AngularJS and I've hit a stumbling block. I can retrieve my jSON and feed it into the frontend, but my problem is coming when I'm going to a new view. My ID is not coming in correctly. Basically if click on my item that has a id 1 its displaying id 14. Or I get TypeError: Cannot read property '14' of undefined
Any ideas would be really helpful.
jSON
[
{
"id": 14,
"title": "new post",
"excerpt": "EXCERPT",
"content": "ushajsd"
},
{
"id": 10,
"title": "last post",
"excerpt": "test",
"content": "test"
},
{
"id": 4,
"title": "middle post",
"excerpt": "contents to post",
"content": "contents to post"
},
{
"id": 1,
"title": "Hello world!",
"excerpt": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
"content": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!"
}
]
AngularJS
//Create main module
var module = angular.module('module', [''])
//Services
module.factory('posts', function($http) {
return {
getAsync: function(callback) {
$http.get('/wp-content/themes/ajax/ajax.php').success(callback);
}
};
});
// Set up our mappings between URLs, templates, and controllers
function caseStudyConfig($routeProvider) {
$routeProvider.
when('/casestudy/:id', {
controller: caseCtrl,
templateUrl: '/wp-content/themes/templates/casestudy.php'
}).
otherwise({
redirectTo: '/'
});
}
// Set up our route so the service can find it
module.config(caseStudyConfig);
//Controllers
function homeCtrl (posts, $scope) {
posts.getAsync(function(data) {
$scope.content = data;
});
}
function caseCtrl (posts, $scope, $routeParams) {
posts.getAsync(function(data) {
$scope.content = data[$routeParams.id];
});
}
Assuming the data property in your getAsync callback is a representation of the JSON you've posted, I think it's because you're attempting to access the object by it's position in the array and not by its id property. If you're using underscore / lodash, you could fix this easily like so:
function caseCtrl (posts, $scope, $routeParams) {
posts.getAsync(function(data) {
// Find the object with id which matches id in route params
$scope.content = _.findWhere(data, { id: $routeParams.id });
});
}
Or you could write your own loop to retrieve the correct object from the collection:
function caseCtrl (posts, $scope, $routeParams) {
posts.getAsync(function(data) {
$scope.content = getObjectById(data, $routeParams.id);
});
function getObjectById(collection, id) {
for (var i = 0, obj; i < collection.length; i ++) {
obj = collection[i];
if (obj.id === id) {
return obj;
}
}
return null;
}
}