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);
Related
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}}.
Here i am calling function getData at every second all is happning good except appending.
every time when function is calling the angularjs is replacing old data to new data.
but i want to append after existing data. any one plz help.
<div ng-app="serviceConsumer">
<div ng-controller="questionsController">
<div ng-repeat="j in LiveChat">
<div>
<div>{{j.UserName2}}</div>
<div>
<div>{{j.Text2}}<div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var app = angular.module('serviceConsumer', []);
app.controller('questionsController', function ($scope, $http) {
$scope.getData = function () {
$http({
method: "GET",
url: "/GetUserDataWebServices.asmx/GetLiveChatListData",
params: {
username: $('.ExeCutiveName').text()
}
})
.success(function (data) {
var myjson = JSON.parse(data);
$scope.LiveChat = JSON.parse(myjson);
//here i want to append myjson to existing ng-repeat <div>
});
}
)};
setInterval($scope.getData, 1000);
</script>
You need to use push method
like $scope.LiveChat.push(JSON.parse(myjson));
concat data instead re-assigned it
Like this
$scope.LiveChat = $scope.LiveChat.concat(JSON.parse(myjson));
I am trying to update the list of the data by getting it from the database. Each time I'll add a data, it will not update the view, the view will only be updated when I refresh the page. I have tried a few solution by using $scope.apply and rearranging the position of my code, those doesn't make a difference. What am I missing here? Below are my code:
JS
//posting post
$scope.post = function(){
$http.post('/post',$scope.post_detail)
.success(function(response){
$scope.render();
});
}
//getting post
$scope.render = function(){
$http.get('/post')
.success(function(response){
$scope.renderPost(response);
});
}
//view post
$scope.renderPost = function(response){
$scope.posts = response;
}
$scope.remove_post = function(id){
$http.delete('/post/'+id).success(function(response){
$scope.render();
});
}
$scope.render();
HTML
<div class="jumbotron text-center" ng-controller="DashboardCtrl">
<h1>{{title}}</h1>
<input type="text" ng-model="post_detail.title" />
<input type="text" ng-model="post_detail.border_color" />
<button ng-click="post(post_detail)">Post</button>
</div>
<div ng-repeat="post in posts">
<p>{{post.title}}</p>
<button ng-click="remove_post(post._id)">Remove</button>
</div>
Note: The remove button works here
Because ng-repeat is outside DashboardCtrl scope. I guess you have a parent controller of the DashboardCtrl div and the posts div and you initiate $scope.posts in the parent controller.
When you have
$scope.renderPost = function(response){
$scope.posts = response;
}
it updates the posts in the child scope. You probably need to do something like:
$scope.$parent.posts = response;
or move the ng-repeat div inside <div class="jumbotron text-center" ng-controller="DashboardCtrl">...</div>
Because you are updating only database.
push newly added post_detail into post object.
//posting post
$scope.post = function(){
$http.post('/post',$scope.post_detail)
.success(function(response){
$scope.post.push($scope.post_detail);
$scope.render();
});
}
I assume your server response to $http.get('/post') is an array of json objects
in that case that array could be nested inside data property
$scope.renderPost = function(response){
$scope.posts = response.data;
}
I have a snippet of code here running in a node application
for( i=0; i < Equipment.length; i += 1 ) {
Equipment[i].NumberForSearch = Equipment[i].ClassPrefix + "-" + Equipment[i].UnitNumber;
console.log(Equipment[i].NumberForSearch);
}
console.log(Equipment[0]);
Equipment is an array of objects and I am trying to add a property to each object in that array called "NumberForSearch".
In my application the way we want to display unit numbers for equipment is "ClasssPrefix"-"UnitNumber". The reason I am wanting to join them here into one variable is that inside my angular application, I want the user to be able to type 12345-12345 inside of a search field which then filters out the Equipment. This doesnt work if I have {{ClassPrefix}}-{{UnitNumber}} for obvious reasons, angular doesnt know that the - even exists.
The problem is that inside my for loop everything is checking out fine. Its logging just as its supposed to, so I figured it worked. When I checked the front end and changed it to display "NumberForSearch", nothing showed up.
I then added the logging statement outside the for loop to check just one of my objects to see if the field even existed and it doesnt. So my question is, why is this snippet not adding the "NumberForSearch" field in my object?
You have to make object with this field before setting to $scope's parameter.
Have a look at init() function.
After adding NumberForSearch field we defined array of objects to parameter in scope.
Of course ng-repeat will loop through it and render elements.
So we will add "| filter:query" to show only needed
<div ng-controller="EquipmentController">
<input type="text" ng-model="query.NumberForSearch" placeholder="search">
<ul>
<li ng-repeat="Item in Equipment | filter:query">{{Item.ClassPrefix}}-{{Item.UnitNumber}}</li>
</ul>
</div>
js part:
var App = angular.module('App', []);
App.controller('EquipmentController', function ($rootScope, $scope, $http, $filter) {
$scope.Equipment = [];
$scope.init = function() {
var request = $http({
method: 'get',
url: '/path/to/equipment/resource'
});
request.success(function (response) {
var Equipment = response.Equipment;
for(var i in Equipment) {
Equipment[i].NumberForSearch = Equipment[i].ClassPrefix + "-" + Equipment[i].UnitNumber;
}
$scope.Equipment = Equipment;
$scope.$apply();
});
}
$scope.init();
});
another way of filtering is to send search field to route, in another word we send query to server and it filters response on serverside.
<div ng-controller="EquipmentController">
<input type="text" ng-model="queryNumber" ng-change="searchByNumber()" placeholder="search">
<ul>
<li ng-repeat="Item in Equipment">{{Item.ClassPrefix}}-{{Item.UnitNumber}}</li>
</ul>
</div>
js part:
var App = angular.module('App', []);
App.controller('EquipmentController', function ($rootScope, $scope, $http, $filter) {
$scope.Equipment = [];
$scope.all = function() {
var request = $http({
method: 'get',
url: '/path/to/equipment/resource'
});
request.success(function (response) {
$scope.Equipment = response.Equipment;
$scope.$apply();
});
}
$scope.all();
$scope.searchByNumber = function() {
var request = $http({
method: 'get',
url: '/path/to/equipment/resource?number='+$scope.queryNumber
});
request.success(function (response) {
$scope.Equipment = response.Equipment;
$scope.$apply();
});
}
});
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
});