How to get the value of the div in jquery? - javascript

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>

Related

Get $id from nested ng-repeat

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.

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 access functions of a controller from within another controller via scope?

I have the following problem, I want to call a function of another controller from within a controller I want to use for a guided tour (I'm using ngJoyRide for the tour). The function I want to call in the other controller is so to say a translator (LanguageController), which fetches a string from a database according to the key given as parameter. The LanguageController will, if the key is not found, return an error that the string could not be fetched from the database. In my index.html fetching the string works, but I want to use it in the overlay element of my guided tour, which does not work, but only shows the "not fetched yet"-error of the LanguageController.
My index.html looks like this:
<body>
<div class="container-fluid col-md-10 col-md-offset-1" ng-controller="LangCtrl as lc" >
<div ng-controller="UserCtrl as uc" mail='#email' firstname='#firstname'>
<div ng-controller="GuidedTourCtrl as gtc">
<div ng-joy-ride="startJoyRide" config="config" on-finish="onFinish()" on-skip="onFinish()">
...
{{lc.getTerm('system_lang_edit')}}
...
</div>
</div>
</div>
</div>
</body>
The controller I'm using for the guided Tour looks like this:
guidedTourModule.controller('GuidedTourCtrl',['$scope', function($scope) {
$scope.startJoyRide = false;
this.start = function () {
$scope.startJoyRide = true;
}
$scope.config = [
{
type: "title",
...
},
{
type: "element",
selector: "#groups",
heading: "heading",
text: " <div id='title-text' class='col-md-12'>\
<span class='main-text'>"\
+ $scope.lc.getTerm('system_navi_messages') + "\
text text text text\
</span>\
<br/>\
<br/>\
</div>",
placement: "right",
scroll: true,
attachToBody: true
}
];
...
}]);
And the output I ultimately get looks like this for the overlay element:
<div class="row">
<div id="pop-over-text" class="col-md-12">
<div id='title-text' class='col-md-12'>
<span class='main-text'>
not fetched yet: system_navi_messages
text text text text
</span>
<br/>
<br/>
</div>
</div>
</div>
...
I hope someone can see the error in my code. Thanks in advance!
Things needs clarity are,
How you defined the 'getTerm' function in your Language controller, either by using this.getTerm() or $scope.getTerm(). Since you are using alias name you will be having this.getTerm in Language controller.
Reason why you are able to access the getTerm function in your overlay element is, since this overlay element is inside the parent controller(Language Controller) and you are referencing it with alias name 'lc' while calling the getTerm function. Thats' why it is accessible.
But the string you pass as a parameter is not reachable to the parent controller. that's why the error message is rendered in the overlay HTML.
Please make a plunker of your app, so that will be helpful to answer your problem.

AngularJS - Cannot set scope value into template

I have following function:
$scope.setDetailToScope = function(data) {
$scope.$apply(function() {
//$scope.order = data;
$rootScope.order = data;
setTimeout(function() {
$scope.$apply(function() {
//wrapped this within $apply
$scope.order = data[0];
console.log('message:' + $scope.order);
console.log($scope.order);
});
}, 100);
});
};
"
console.log($scope.order);
Gives me values which has been set into scope.
But i cannot get these values in template.
<!-- DEBUG DIV -->
<div class="debugDiv" ng-show="$root.debugable == true">
{{columns}}
</div>
<div data-ng-controller="OrdersCtrl" ng-init="initData()">
<div id="orders_grid" >
</div>
</div>
<!-- GRID TOOLBAR BUTTON TEMPLATE -->
<script id="template" type="text/x-kendo-template">
<a class="k-button" href="\#/orders/create">Add</a>
</script>
<!-- ORDER DETAIL DIV -->
<div class="container" id="orderDetail" data-ng-controller="OrdersCtrl" ng-if="'detailSelected == true'" xmlns="http://www.w3.org/1999/html">
<!-- DEBUG DIV -->
<div class="debugDiv" ng-show="$root.debugable == true">
{{order}} <!--NOT WORKING-->
</div>
If i tried to add values into rootscope it works, but in this case i cannot get value into ng-model.
What i'm doing wrong please?
Many Thanks for any help.
EDIT:
If i tried solution wit $timeout i got on console.log($scope.order);
following object which is not passed into the template:
_events: ObjectacrCrCode: "interlos"actionName: ht.extend.initarchived: falsebaseStationInfo: ht.extend.initbsc: "bsc1"btsRolloutPlan: "plan1"candidate: "B"costCategory: ht.extend.initcreatedBy: ht.extend.initdirty: falsefacility: ht.extend.initid: 3location: ht.extend.initmilestoneSequence: undefinednetworkType: "Fix"note: "poznamka"orderNumber: 111113orderType: ht.extend.initotherInfo: ht.extend.initparent: function (){return e.apply(n||this,r.concat(h.call(arguments)))}partner: ht.extend.initpersonalInfo: ht.extend.initproject: ht.extend.initpsidCode: "psid1"sapSacIrnCode: "sap1"uid: "924c0278-88d0-4255-b8ac-b004155463fa"warehouseInfo: ht.extend.init__proto__: i
well I'm not sure why you are using a setTimeout with scope apply, to me is safer to use a $timeout since it fires another digest cycle,
try something like
$scope.setDetailToScope = function(data) {
$timeout(funtion(){
//$rootScope.order = data; try either data or data[0]
$scope.order = data[0];
},100);
};
please note that calling nested apply methods can run into some problems with the angularjs digest cycle you may get an error like "digest already in progress" so put attention to it.
NOTE:
it seems like you got some dirty data there, so try to do a map between the data and the scope
$scope.order ={};
$scope.order.uid = data.uid;
$scope.order.orderNumber = data.orderNumber //and so on
in your template try something like:
<div class="debugDiv">
<p> {{order.uid}} </p>
<p> {{ order.orderNumber}} </p>
</div>
this could be a little bit rustic but it worth to try it out.

AngularJS updating specific fields with new data

Say, I have the following code:
<div ng-controller="postsController">
<div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts">
......
<div class="comments">
<div><span>{{post.totalcomments}}</span> Comments</div>
</div>
.......
</div>
</div>
and on page load this evaluates to something like:
<div ng-controller="postsController">
<div id = "post_id_1" class = "post">
......
<div class="comments">
<div><span>3</span> Comments</div>
</div>
.......
</div>
<div id = "post_id_2" class = "post">
......
<div class="comments">
<div><span>6</span> Comments</div>
</div>
.......
</div>
....and so on.....
</div>
How could I then (using a different controller?) update the DOM when there is a change in the post.totalcomments value for a particular post? I've got the backend worked out, and know you can use $timeout to have a controller repeat itself. I would do it with jQuery (messy but easy) like this (eg: post #1 had a new comment):
var newtotal = 4; //but really get the value from ajax call
$("#post_id_1 .comments span").html(newtotal)
But how would I do this with Angular? I don't want to re-display all the posts and the data, every time I check for updated with the server. Just have a controller (which refreshes with $timeout) and only update the changed fields as needed.
Thanks
If you want to refresh the data periodically use $interval rather than timeout, If its going to be only once after a certain perios say 10 seconds use $timeout. And you need not write a separate controller for this. This can be done within the same controller.
A simple interval demo for you,
Sample Demo: http://plnkr.co/edit/fj6crcHkxm6rkwJT9eGg?p=preview
JS:
app.controller('MainCtrl1', function($scope, $timeout, $http, $interval) {
$scope.comments = [{
total: 3,
comment: 'some comment 1'
}, {
total: 10,
comment: 'some other comment'
}];
$interval(function(){
//logic to update comments
$scope.comments[0].total++;
},1000);
$scope.updateCount = function(){
$scope.comments[1].total++;
};
});

Categories

Resources