Get $id from nested ng-repeat - javascript

I have a post/comment system in Angularjs and Firebase, I can loop without problem to show all the post with ng-repeat and its comments as well. The problem start when I tried to get the $id from the second nested ng-repeat to be able to save the replies into the comment. Let's see the code I have:
<div class="posts" ng-repeat="post in posts">
<div>{{post.text}}</div>
<div>
<input type="text" placeholder="Comment here..." ng-model="comment">
<button ng-click="addComment(post, comment)"></button>
</div>
<div class="comments" ng-repeat="cmt in post.comments">
<p>{{cmt.text}}</p>
<div>
<input type="text" ng-model="answer">
<button ng-click="addAnswer(cmt, post)"></button>
</div>
<div ng-repeat="answer in cmt.answers">
<p>{{answer.text}}</p>
</div>
</div>
</div>
app.js
$scope.addComment = function(post, comment){
var ref = new Firebase("https://url.firebaseio.com/users/" + post.$id + "/comments");
var comments = $firebaseArray(ref);
comments.$add({
text: comment
});
}
$scope.addAnswer = function(cmt, post){
var refanswers = new Firebase("https://url.firebaseio.com/users/" + post.$id + "/comments/" + cmt.$id + "/answers");
var answers = $firebaseArray(refanswers);
answers.$add({
text: answer
});
}
To test, first I remove the code above inside addAnswer function and write two console.log to check if Im getting the values
console.log(post.$id);
console.log(cmt.$id);
I get only the post.$id but no the second one (undefined), am I missing something about nested ng-repeat?
Edited: I changed the code to avoid the $scope conflict following the answers below but still does not work.
Any advice is welcome, thanks :)

comment being passed into addAnswer() is likely not the instance object of the ng-repeat as you are thinking, rather it could be clashing with the ng-model='comment' already defined above. You have a scope issue.
This may be fixed by changing ng-repeat="comment in post.comments" to ng-repeat="cmnt in post.comments"or whatever you want to name it, as long as it doesn't conflict with previously defined $scope objects.

Related

How to get the value of the div in jquery?

I am using JQUERY in my angularjs project since in some special conditions(AMP).
<div data-ng-repeat = "comment in blog.comments">
<i class="icon-edit font20 edit-faq-icon pointer" id="edit-comment" data-ng-click="editComment(comment);"></i>
</div>
Previously I had ng-click and now I can only find event by jquery.
$('#edit-comment').click(function(){
alert('hi');
})
But I want to access the parameter passed(comment) in the function editComment(comment).
Write a scope function in your angular controller like the below function. You will get the comment as parameter.
$scope.editComment=function(comment)
{
$scope.comment=comment;
};
Set an html content like this.
<div ng-model="comment" id="Comment"></div>
Now you can use
$('#Comment').val() to get the value in click
you can use .text() method to get the value of div.
also you can refer the following link http://api.jquery.com/text/
You can get the comment by passing the comment as a parameter to ng-click function.
var app = angular.module("myApp", []);
app.controller("myCntrlr",function($scope){
$scope.blog=
{
name:"Naresh",
comments:["test comment 1","test comment 2","test comment 3"]
}
$scope.editComment = function(comm){
alert(comm);
};
});
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js'></script>
<div ng-app="myApp" ng-controller="myCntrlr">
<div ng-repeat = "comment in blog.comments">
<button ng-click="editComment(comment);">get Comment</button>
</div>
</div>

Cannot Access Fields after adding Array to another Array

I have an array of sections where a section is pushed into the array when the user clicks a checkbox. It is defined like this:
$scope.print = {
sections:[]
};
Once I have all of the selected Sections, I use a service to get a list of questions for each selected section like this:
var questions = [];
myService.getQuestions(id)
.success(function (data) {
questions = data;
});
Then I assign the returned questions to the original array like this:
angular.forEach($scope.print.sections,
function (value, key) {
if (value.QuestionSectionID === id) {
$scope.print.sections[key].questions = questions;
}
});
The assignment "seems" to work, but I am unable to access the particular fields in the questions array by their field names.
On my HTML page, I have this:
<div ng-repeat="ps in print.sections">
<div>
<h4>{{ps.vchSectionName}}</h4>
</div>
<div ng-repeat="section in ps.questions">
<div ng-repeat="q in section">
{{q.vchQuestionText}}
</div>
</div>
</div>
When I try to access the "q.vchQuestionText" field, my HTML is blank, however if I simple do the following:
<div ng-repeat="q in section">
{{q}}
</div>
I can then see ALL of the information contained in each field of "q". But I need to access each field in "q" by it's name. What am I missing here?
Any assistance is greatly appreciated!
Okay, the reason I could display all the data in "q", but could not specify a field is because I had one too many ng-repeat directives.
All I needed was the following:
<div ng-repeat="ps in print.sections">
<div>
<h4>{{ps.vchSectionName}}</h4>
</div>
<div ng-repeat="q in ps.questions">
{{q.vchQuestionText}}
</div>
</div>
Hopefully, this will help someone else. Thank you all for your help.

adding an array property to object in angular js

I have an object called user:
It has properties like user.name, user.age e.tc.
Now, I need to add an array to user object called subjects via ng-model.
This is what i did inside of ng-repeat:
<input type="text" ng-model="user.subjectname[$index]"
name="subject" ng-required="true" placeholder="Enter a subject name">
and when I do console.log(user.subjectname), it looks like this:
Now, after this, I wanted to do something like this:
<div ng-repeat="data in user.sujects">
<td>{{data}} </td>
</div>
But it does not work.
Try2:
In my my service that is called from controller, I tried this,
if(dataArray== null)
var dataArray=[];
console.log("scop.user.subjectname...................." + user.subjectname);
for(var i in user.subjectname)
{ dataArray.push(user.subjectname[i])
}
user.data=dataArray;
so, now if I do,
<div ng-repeat="data in user.data">
<td>{{data}} </td>
</div>
I still get nothing.
Can I get some direction to deal with this?
Like I told you in your previous question, and showcased in a jsbin.
You need to use the (key, val) in object syntax to get those values out of user.subjectname
ng-repeat="(key, val) in user.subjectname" ng-bind="val"
If you need to transform this object into an array:
$scope.arr = [];
Object.keys(user.subjectname).forEach(function (key) {
arr.push(user.subjectname[key]);
});
Then if you need to output that
ng-repeat="a in arr" ng-bind="a"
edit: after further explanation from you, I'm assuming this jsBin highlights something close to what you are after.

binding to controller object in Angular

I'm new to angular, trying to bind an an element's content into the controller's Scope to be able to use it within another function:
here is the scenario am working around:
I want the content of the <span> element {{y.facetName}} in
<span ng-model="columnFacetname">{{y.facetName}}</span>
to be sent to the controller an be put in the object $scope.columnFacetname in the controller
Here is a snippet of what I'm working on:
<div ng-repeat="y in x.facetArr|limitTo: limit track by $index ">
<div class="list_items panel-body ">
<button class="ButtonforAccordion" ng-click="ListClicktnColumnFilterfunc(); onServerSideButtonItemsRequested(ListClicktnColumnFilter, myOrderBy)">
<span>{{$index+1}}</span>
<span ng-model="columnFacetname">{{y.facetName}}</span>
<span>{{y.facetValue}}</span>
</button>
</div>
</div>
angular.module('mainModule').controller('MainCtrl', function($scope, $http) {
$scope.columnFacetname = "";
$scope.ListClicktnColumnFilter = "";
$scope.ListClicktnColumnFilterfunc = function() {
$scope.ListClicktnColumnFilter = "\":\'" + $scope.columnFacetname + "\'";
};
}
the problem is that the $scope.ListClicktnColumnFilter doesn't show the $scope.columnFacetname within it, meaning that the $scope.columnFacetname is not well-binded.
In your ng-click instead of calling two different function
ng-click="ListClicktnColumnFilterfunc(); onServerSideButtonItemsRequested(ListClicktnColumnFilter, myOrderBy)"
you can declare like this
ng-click="columnFacetname = y.facetName; onServerSideButtonItemsRequested(columnFacetname , myOrderBy)"
You are trying to pass that model to another function by assigning it to ListClicktnColumnFilter in your controller
By doing in this way, you can achieve the same thing.
I have done one plunker with sample array,
http://embed.plnkr.co/YIwRLWXEOeK8NmYmT6VK/preview
Hope this helps!

How to add multiple items to a list

I'm building an app where users can add items to a list and I decided, for the sake of learning, to use Angular (which I'm very new to). So far, I've been able to successfully add a single item to that list without any issues. Unfortunately, whenever I try to add more than one without a page refresh, I get an error - specifically a "Undefined is not a function."
I've spent more time than I care to think about trying to resolve this issue and I'm hoping an expert out there can give me a hand. Here's what I have so far:
Controllers:
angular.module('streakApp')
.controller('StreakController', function($scope) {
// Removed REST code since it isn't relevant
$scope.streaks = Streak.query();
// Get user info and use it for making new streaks
var userInfo = User.query(function() {
var user = userInfo[0];
var userName = user.username;
$scope.newStreak = new Streak({
'user': userName
});
});
})
.controller('FormController', function($scope) {
// Works for single items, not for multiple items
$scope.addStreak = function(activity) {
$scope.streaks.push(activity);
$scope.newStreak = {};
};
});
View:
<div class="streaks" ng-controller="FormController as formCtrl">
<form name="streakForm" novalidate >
<fieldset>
<legend>Add an activity</legend>
<input ng-model="newStreak.activity" placeholder="Activity" required />
<input ng-model="newStreak.start" placeholder="Start" type="date" required />
<input ng-model="newStreak.current_streak" placeholder="Current streak" type="number" min="0" required />
<input ng-model="newStreak.notes" placeholder="Notes" />
<button type="submit" ng-click="addStreak(newStreak)">Add</button>
</fieldset>
</form>
<h4>Current streaks: {{ streaks.length }}</h4>
<div ng-show="newStreak.activity">
<hr>
<h3>{{ newStreak.activity }}</h3>
<h4>Current streak: {{ newStreak.current_streak }}</h4>
<p>Start: {{ newStreak.start | date }}</p>
<p>Notes: {{ newStreak.notes }}</p>
<hr>
</div>
<div ng-repeat="user_streak in streaks">
<!-- Removed most of this for simplicity -->
<h3>{{ user_streak.fields }}</h3>
</div>
</div>
Could you post the html of StreakController too? Your solution works fine in this fiddle:
http://jsfiddle.net/zf9y0yyg/1/
.controller('FormController', function($scope) {
$scope.streaks = [];
// Works for single items, not for multiple items
$scope.addStreak = function(activity) {
$scope.streaks.push(activity);
$scope.newStreak = {};
};
});
The $scope inject in each controller is different, so you have to define the "streaks" in FormController.
Your problems comes from :
.controller('FormController', function($scope) {
// Works for single items, not for multiple items
$scope.addStreak = function(activity) {
$scope.streaks.push(activity);
^^^^^^
// Streaks is initialized in another controller (StreakController)
// therefore, depending of when is instantiated StreakController,
// you can have an error or not
$scope.newStreak = {};
};
});
A better design would be to implement a StreakService, and to inject that service in the controller you need it. Of course, initializing $scope.streaks in FormController will make your code work, but that's not the responsibility of FormController to initialize this data.
I assume FormController is a nested controller of StreakController, so they share the same scope.
if that works for single object, it should work for mulitiple objects, the problems is you can't just use push to push an array of object to the streaks, you can for loop the array and add them individually or use push.apply trick. I thought the reason of Undefined is not a function. is because the Stack.query() return an element instead of an array of elements so, the method push doesn't exists on the $scope.streaks.
http://jsbin.com/jezomutizo/2/edit

Categories

Resources