Angularjs $http get json data, but won't display - javascript

I am new to angularjs, and I try to async load data by using angularjs.
Json Sample
[{"id":153,"name":"Computer Parts->Cooling Device->CPU Fan"},{"id":30,"name":"Computer Parts->CPU"}]
HTML Code
var homeApp = angular.module('managementApp',[]);
homeApp.controller('categoryMgmt',function($scope,$http){
$scope.categoryFilter = '';
$scope.categorys = '';
$scope.categoryLoad = function(){
var key = $scope.categoryFilter;
$http({
method : 'get',
url : 'hugo.dev/api/categorys/'+key,
}).then(function mySuccess(response){
$scope.categorys = angular.fromJson(response.data);
console.log($scope.categorys[0].name);
});
};
});
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<div class="panel-body" ng-app="managementApp" ng-controller="categoryMgmt">
<div class="form-group col-md-6">
<label for="category">Category</label>
<input name="categoryName" class="form-control" ng-model="categoryFilter">
<div class="list-group" ng-show="categoryFilter" >
<a ng-repeat="item in categorys" href="#" class="list-group-item">{{ item.name }}</a>
</div>
</div>
<button type="button" ng-click="categoryLoad()">asd</button>
</div>
Console Output
Computer Parts->Cooling Device->CPU Fan
The question is, ng-repeat work fine, there are two tags appead in the list,but {{ item.name }} can not read any data. I don't know why.The result #SnapShot, Please Help!

There isn't anything wrong with the code you posted. As Alexander pointed out, you probably don't need fromJson(), but that shouldn't be a problem either.
Here is a working plunker using your same code: https://plnkr.co/edit/GrYZZLjYc9mwCj7dAs5Z?p=preview
The only thing I changed was to pull the data from file since I don't have your service:
// url : 'hugo.dev/api/categorys/'+key,
url: 'data.json'
I guess this isn't necessarily an answer to your problem, but it proves that the code you posted works... your issue must be elsewhere.

scope.categorys must be initialize to array and remove fromJson
homeApp.controller('categoryMgmt',function($scope,$http){
$scope.categoryFilter = '';
// Default to array
$scope.categorys = [];
$scope.categoryLoad = function(){
var key = $scope.categoryFilter;
$http({
method : 'get',
url : 'hugo.dev/api/categorys/'+key,
}).then(function mySuccess(response){
// remove fromJson
$scope.categorys = response.data;
console.log($scope.categorys[0].name);
});
};

I think you should use $scope.category in the html code instead of {{item.category}}.

Related

angularjs: how to store the function returning value in one variable . based on ng-repeat

hi i am getting the intrestedid from ng-repeat , i want to call another service and store that data in one variable dynamically , because need send seperate api for getting images.
my html is look like this
<div class="" ng-repeat="item in items" >
<div ng-init="MyPic = getMyprofile(item.interestedTo)">
<img src="{{MyPic}}">
</div>
</div>
My controller is look like this.
$scope.getMyprofile = function(IntrstdId){
appServices.profile( IntrstdId, function(response){
$scope.meDetails = response.data;
})
return $scope.meDetails;
}
My services is look like this.
service.profile= function(userId, callback) {
path = serviceUrl + '/profile/'+ userId;
$http({
method: 'GET',
url: path
}).then(function(data) {
callback(data)
}, function(data) {});
}
but its getting undefined , any issues in this code.
I tried to resolve this by creating some abstract stub, that may be helpful to you. Please review and let me know if issue still arise
HTML
<div ng-repeat ="data_ in parentData track by $index">
<ul>
<li ng-repeat="result in data_.data track by $index" ng-init="counter=increaseCounter();">
<div ng-model="counter"></div>
</ul>
</div>
Controller
// It simply store variable value in scope.counter
$scope.counter = 0;
$scope.increaseCounter = function () {
var cnt = $scope.counter++;
return cnt;
};
//Another way is to call service while update variable vaule
$scope.counter = 0;
$scope.increaseCounter = function () {
var cnt = $scope.counter++;
AppService.updateValue(cnt);
return cnt;
};
$scope.getMyprofile = function(IntrstdId){
appServices.profile( IntrstdId, function(response){
$scope.meDetails = response.data;
})
return $scope.meDetails;
}
I think issue is this function. appService.profile is asyncronize method and before complete it function return $scope.meDetails;
my suggestion is to hardcore some value like in below and see the result. if it is working then you have to change the function accordingly.
$scope.meDetails ='some value';
return $scope.meDetails;
There are several best practice issue along with the async problem.
1.Avoid using ng-init unless you want to re-run the function when you reconstruct the element, for instance ng-if. It is more so when you use ng-repeat without track by, any changes in the data source would re-trigger all ng-init in the children.
Solution: Run them when you init the controller, or as soon as $scope.items is filled.
angular.forEach($scope.items, function(item) {
appServices.profile(item).then(function(data){
item.myPic = data;
});
});
<div class="" ng-repeat="item in items" >
<img src="{{item.myPic}}">
</div>
2.The correct way to wrap a function that returns promise (which $http is) is to return the function itself. You can research more on how to pass the resolved/rejected result around.
// not needed anymore, just to showcase
$scope.getMyprofile = function(IntrstdId){
return appServices.profile( IntrstdId );
}
// same goes with the service function
service.profile= function(userId) {
path = serviceUrl + '/profile/'+ userId;
return $http({
method: 'GET',
url: path
}).then(function(response) {
return response.data;
});
}

How to display a returned json in angular view?

I am implementing a search in the github repository.
I need to display the information that i get from here: https://api.github.com/search/repositories?q=bootstrap . for instance into a view or HTML
<div ng-app="newsearchApp">
<div ng-controller="MainCtrl">
<form action="#/about" method="get">
<input ng-model="searchText" />
<button ng-click="search()">Search</button>
</form>
</div>
</div>
the code for searching the Github repository;
angular.module('newsearchApp')
.controller("MainCtrl", ["$scope", function($scope) {
$scope.searchText = "";
$scope.search = function() {
console.log($scope.searchText);
var item = $scope.searchText;
// console.log(item)
var GithubSearcher = require('github-search-api');
var github = new GithubSearcher({username: 'test#something.com', password: 'passwordHere'});
var params = {
'term': $scope.searchText
};
//i am not certain about the 'userData'
github.searchRepos(params, function(data) {
console.log(data);
$scope.userData = data; //i am not certain about the 'repoData'
});
} }]);
the problem is here, when populating the json object to HTML
<div ng-repeat="repo in userData | filter:searchText | orderBy:predicate:reverse" class="list-group-item ">
<div class="row">
<div class="col-md-8">
<h4>
<small>
<span ng-if="repo.fork" class="octicon octicon-repo-forked"></span>
<span ng-if="!repo.fork" class="octicon octicon-repo"></span>
<small>{{repo.forks_count}}</small>
</small>
<a href="{{repo.html_url}}" target="_blank" >
{{repo.name}}
</a>
<small>{{repo.description}}</small>
<small>{{repo.stargazers_count}}</small>
<a href="{{repo.open_issues_count}}" target="_blank" >
Open Issues
</a>
<small>{{}}</small>
</h4>
</div>
</div>
</div>
the results are null on the HTML but are not null on the console.
thanks in advance
the results are null
The problem is, that Angular doesn't notice that the GitHub server has answered and doesn't update the view. You have to tell Angular manually to re-render the view. Try calling $scope.$apply():
github.searchRepos(params, function(data) {
console.log(data);
$scope.userData = data;
$scope.$apply();
});
If you'd make your request to the GitHub API with Angulars $http service, then this would not be needed - you'll only need $scope.$apply() if something asynchronous happens which doesnt live in the "Angular world" - for example things like setTimeout, jQuery ajax calls, and so on. That's why there are Angular wrappers like $timeout and $http.
More details: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
The GitHub API can be accessed using the AngularJS $http service:
app.controller("myVm", function($scope,$http) {
var vm = $scope;
var url = "https://api.github.com/search/repositories?q=bootstrap"
$http.get(url).then(function onSuccess(response) {
vm.data = response.data;
console.log(vm.data);
})
})
HTML
<div ng-app="myApp" ng-controller="myVm">
<div ng-repeat="item in data.items">
{{item.full_name}}
</div>
</div>
The DEMO on JSFiddle
Since you're not using the Angular $http service, angular is not aware of the changes. You need to manually tell Angular to re-render and evaluate by using
$scope.$apply();

Ng-repeat is not displaying json data

thanks advance for any support. So I have a factory that uses a post to get some data from a C# method. That all seems to be working as I can see the data in the console log when it gets returned. However, when I get the data, I can't seem to get it to display properly using ng-repeat.
I've tried a couple different ways of nesting ng-repeats and still no luck. So now I'm thinking I may have not passed the data from the call properly or my scope is off. I've also tried passing data.d to hangar.ships instead of just data. Still pretty new to angular so in any help to point me int he right direction is greatly appreciated.
app code:
var app = angular.module('shipSelection', ['ngRoute', 'ngResource']);
app.controller('ShipController', function ($scope, ShipService) {
var hangar = this;
hangar.ships = [];
var handleSuccess = function (data, status) {
hangar.ships = data;
console.log(hangar.ships);
};
ShipService.getShips().success(handleSuccess);
});
app.factory('ShipService', function ($http) {
return {
getShips: function () {
return $http({
url: '/ceresdynamics/loadout.aspx/getships',
method: "post",
data: {},
headers: { 'content-type': 'application/json' }
});
}
};
});
Markup:
<div class ="col-lg-12" ng-controller="ShipController as hangar" >
<div class =" row">
<div class="col-lg-4" ><input ng-model="query" type="text"placeholder="Filter by" autofocus> </div>
</div><br />
<div class="row">
<div ng-repeat="ship in hangar.ships | filter:query | orderBy:'name'">
<div class="col-lg-4">
<div class="panel panel-default">
<div>
<ul class="list-group">
<li class="list-group-item" >
<p><strong>ID:</strong> {{ ship.ShipID }} <strong>NAME:</strong> {{ ship.Name }}</p>
<img ng-src="{{ship.ImageFileName}}" width="100%" />
</li>
</ul>
</div>
</div><!--panel-->
</div> <!--ng-repeat-->
</div>
</div>
</div> <!--ng-controller-->
JSON returned from the post(From the console.log(hangar.ships):
Object
d: "[{"ShipID":"RDJ4312","Name":"Relentless","ImageFileName":"Ship2.png"},{"ShipID":"ZLH7754","Name":"Hercules","ImageFileName":"Ship3.png"},{"ShipID":"FER9423","Name":"Illiad","ImageFileName":"Ship4.png"}]"
__proto__: Object
As per AngularJS version 1.2, arrays are not unwrapped anymore (by default) from a Promise (see migration notes). I've seen it working still with Objects, but according to the documentation you should not rely on that either.
Please see this answer Angular.js not displaying array of objects retrieved from $http.get
What happens if you add JSON.parse(data);
If this works you should add some checks in and perhaps migrate that logic to the service. Or use $resource per the other answer.
https://github.com/angular/angular.js/commit/fa6e411da26824a5bae55f37ce7dbb859653276d

AngularJS Push New Data into Specific JSON

I've got a JSON output that looks like this:
[{"id":"121","title":"Blog Title","content":"Blog content"}, "comments":[{"id":"12","content":"This is the comment."}]]
I'm retrieving the array through a controller in Angular:
app.controller('BlogController', function($scope, $http) {
var blog = this;
blog.posts = [];
$http.get('/process/getPost.php').success(function (data) {
blog.posts=data;
});
$scope.submitComment = function() {
blog.posts.concat($scope.formData);
$http({
method : 'POST',
url : '/process/insertComment.php',
data : $.param($scope.formData), // pass in data as strings
headers: {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.success(function(data) {
console.log(data);
$scope.formData.comment="";
});
};
})
Then displaying the information in my index.html file:
<div ng-controller="BlogController as blog" ng-cloak class='ng-cloak'>
<div ng-repeat="post in posts">
<div>{{post.title}}</div>
<div>{{post.content}}</div>
</div>
<div ng-repeat="comment in post.comments">
{{comment.content}}
</div>
<form name="commentform" ng-init="formData.id=post.id" novalidate>
<textarea ng-model="formData.comment" name="comment" required></textarea><br>
<input type="submit" ng-disabled="commentform.$invalid" value="Submit" ng-click="submitComment()">
</form>
</div>
Everything works as it should but I've been trying to have the submitComment() update comment.content inside JSON array where the blog id equals post.id and where the comment id equals comment.id.
I've tried doing blog.post.comment.push($scope.formData) but that didn't work. Any idea why it doesn't work and how to fix it?
That might help you http://jsbin.com/fatote/2/edit?html,js,output
$scope.submitComment = function(post) {
$http.post('/process/insertComment.php', post.formData)
.then(function(data) {
console.log(data);
$scope.formData.comment="";
}, function(){
alert("Can't post");
}).then(function(){
//finally as we know that post would work in that case
//find last comment id
var newCommentId = post.comments[post.comments.length-1].id +1;
//create new comment obj
var newComment = {
id:newCommentId,
content:post.formData.comment
};
//push comment in comments array
post.comments.push(newComment);
//clean form
post.formData.comment="";
});
};
Your line blog.posts.concat($scope.formData); isn't being assigned anywhere. Note that .concat is different from .sort in that you're creating a new array.
From MDN: "The concat() method returns a new array comprised of this array joined with other array(s) and/or value(s)."
Try changing your line to blog.posts = blog.posts.concat($scope.formData);
edit:
I'm guessing at your data format, more likely the change needed is:
var post = blog.posts[blogPostId]; // you'll need to determine blogPostId
post.comments = post.comments.concat($scope.formData);

Updating multi-model form from Angular to Sinatra

I'm currently having an issue with updating a form in Angular and pushing the update through to Sinatra.
It is supposed to:
When clicked, the form to edit the current item is shown (current data for each field is displayed from the item scope).
When submitted, it is attempting to update to a different scope (updateinfo). I am not sure but do I need a way of using multiscope or one scope to allow it to update?
At present the script sends the correct downloadID parameter, but the JSON from the scope submitted is as I believe, incorrect.
Also, I'm not sure whether the Sinatra app.rb syntax is correct, for someone new to these frameworks, it has been hard to find useful documentation online.
If anybody could help it would be very much appreciated.
downloads.html
<div ng-show="showEdit">
<form ng-submit="updateinfo(item.downloadID); showDetails = ! showDetails;">
<div class="input-group"><label name="title">Title</label><input type="text"
ng-model="item.title"
value="{{item.title}}"/></div>
<div class="input-group"><label name="caption">Download caption</label><input type="text"
ng-model="item.caption"
value="{{item.caption}}"/>
</div>
<div class="input-group"><label name="dlLink">Download link</label><input type="url"
ng-model="item.dlLink"
value="{{item.dlLink}}"/>
</div>
<div class="input-group"><label name="imgSrc">Image source</label><input type="url"
ng-model="item.imgSrc"
value="{{item.imgSrc}}"/>
</div>
<!-- download live input types need to be parsed as integers to avoid 500 internal server error -->
<div class="input-group"><label name="imgSrc">
<label name="dlLive">Download live</label><input type="radio" ng-model="download.dl_live"
value="1"/>
<label name="dlLive">Not live</label><input type="radio" ng-model="download.dl_live"
value="0"/></div>
<div class="input-group"><label name="imgSrc"><input type="submit"/></div>
</form>
controllers.js
$scope.loadData = function () {
$http.get('/view1/downloadData').success(function (data) {
$scope.items = data;
});
};
$scope.loadData();
$scope.updateinfo = function(downloadID) {
id = downloadID
var result = $scope.items.filter(function( items ) {
return items.downloadID == id;
});
console.log(result);
updatedata = $scope.items
$http({
method : 'PUT',
url : '/view1/downloadedit/:downloadID',
data : result
});
};
app.rb
#edit download
put '/view1/downloadedit' do
puts 'angular connection working'
ng_params = JSON.parse(request.body.read)
puts ng_params
#download = Download.update(ng_params)
end
The wrong scope was attempting to be used. Once the scope was corrected to items, the correct JSON was being routed:
$scope.updateinfo = function(downloadID) {
id = downloadID
var result = $scope.items.filter(function( items ) {
return items.downloadID == id;
});
console.log(result);
updatedata = $scope.items
$http({
method : 'PUT',
url : '/view1/downloadedit/:downloadID',
data : result
});

Categories

Resources