Function automatically called in some condition - angularjs

I have code like this:
<div class="row"
ng-repeat="x in companies|orderBy:'id' ">
<div class="col left" >
<button ng-click="viewPublicId(x.id)">{{x.companyname}}</button>
</div>
<div class="col left">
{{x.address}}
</div>
<div class="col left">
{{x.telephone}}
</div>
</div>
What I want to do is add a check: when companies.size=1, function viewPublicId is automatically called. How can I achieve that? Thanks.
updated: viewPublicId function:
$scope.viewPublicId = function viewPublicId(companyid) {
var url = "http://7cf8d64c.tunnel.mobi/yii2-basic/web/index.php?r=restpublic/view&companyid=" + companyid;
console.log("debug", url);
$http.get(url)
.success(function (response)
{
console.log("debug PublicId",response);
if(response.length==33)
$scope.publicids = null;
else
$scope.publicids = response;
})
.error(function (response)
{
console.log("debug PublicId",response);
$scope.publicids = null;
});
$state.go('tabs.publicidlist');
}

In you controller:
if ($scope.companies.length === 1) {
$scope.viewPublicId();
}
If your companies could be changed dynamically, and you need to call the function everytime it changes, use $watch:
$scope.$watch('companies', function () {
if ($scope.companies.length === 1) {
$scope.viewPublicId();
}
}, true);

Related

Can't display ng-repeat child scope property

I need to display a list of data records using ng-repeat. Within every data object entry (a coupon) displyed, I need to grab some properties ($scope.etabName and $scope.etabDistance) from that object, do some calculations and show the result in the same data object's view within the ng-repeat view.
I've managed to do the calculations and when I console.log them the results are correct, but they are not showing correctly: the property displyed is the one relative to the last data object iterated by ng-repeat.
I know I'm not understanding the Angular way of doing scopes, so any help is welcome.
My controller:
$scope.getCouponList = function () {
$http({
method: 'JSONP',
url: $scope.couponListUrl + "?callback=JSON_CALLBACK&cookie=" + $localStorage.user.cookie +
"&usr_latitude=" + $rootScope.lat + "&usr_longitude=" + $rootScope.lng
}).
success(function (data, status) {
if (data.status && data.status == "ok") {
$rootScope.couponList = data.list;
}
}).error(function (data, status, headers, config) {
});
$scope.fetchEtabDetails = function($stateParams) {
_.select($stateParams.etablissement, function (etab) {
if (etab.id === $stateParams.etabcloser) {
$scope.etabName = etab.name;
$scope.etabDistance = etab.distance;
}
});
};
};
My view:
<ion-content scroll="true" ng-controller="getCouponList">
<ion-list>
<ion-item class="decline" ng-repeat="coupon in couponList"
ng-click="fetchCouponDetails(coupon)"
ng-init="fetchEtabDetails(coupon)">
<div class="offer-image">
<img class="full-image" ng-src="{{coupon.image_operation}}">
<div class="offer-logo">
<img ng-src="{{coupon.enseigne_logo_url}}">
</div>
<div class="offer-ens-name">
<span>{{coupon.ens_name}}</span>
</div>
<div class="offer-name wrap-txt">
<span>{{coupon.name}}</span>
</div>
<div class="offer-deadline-details">
<i class="icon ion-android-time"></i>
<timer countdown="coupon.diff_date" max-time-unit="'year'" interval="1000">{{ddays}}:{{hhours}}:{{mminutes}}</timer>
</div>
<div class="offer-zone">
<i class="icon ion-location" class="etab"></i>
<span>{{etabName}} {{etabDistance}} km</span>
</div>
</div>
</ion-item>
</ion-list>
</ion-content>
In this function:
$scope.fetchEtabDetails = function($stateParams) {
_.select($stateParams.etablissement, function (etab) {
if (etab.id === $stateParams.etabcloser) {
$scope.etabName = etab.name;
$scope.etabDistance = etab.distance;
}
});
You only have 1 $scope.etabName. Each call is overwriting it.
I would do this...
$scope.fetchEtabDetails = function($stateParams) {
_.select($stateParams.etablissement, function (etab) {
if (etab.id === $stateParams.etabcloser) {
$stateParams.etabName = etab.name;
$stateParams.etabDistance = etab.distance;
}
});
then in your HTML...
<div class="offer-zone">
<i class="icon ion-location" class="etab"></i>
<span>{{coupon.etabName}} {{coupon.etabDistance}} km</span>
</div>

Different template on angular

On my HTML code I want to display either a gallery of images or just one image ... The templates are different:
if (mode = 0) {
<div data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in model.images'>
<img data-ng-src="image.Url"/>
// Some more code
</div>
</div>
} else {
<div data-ng-controller="ImageController" class="image">
<img src="data-ng-src="{image.Url}" />
// Other code
</div>
}
On angular controller I have the following:
application.controller('ImageController', function ImageController($scope, ImageService) {
$scope.model = {
images: []
}
var init = function () {
ImageService.GetList($scope.model.pages.instagram)
.success(function (data, status, headers, config) {
$scope.model.images = $scope.model.images.concat(data.Images);
})
.error(function (data, status, headers, config) { });
}
How to modify the controller to display either a list of images or one single image?
HTML
<script type="text/javascript">
window.isMultiple = '#RazorIsMultiple';
</script>
<div data-ng-controller="ImageController" class="gallery">
<!--<input type="hidden" data-ng-model="mode.isMultiple" value="#RazorIsMultiple"/>-->
<div data-ng-if="mode.isMultiple" data-ng-repeat='image in model.images'>
<img data-ng-src="image.Url"/>
// Some more code
</div>
<img data-ng-if="!mode.isMultiple" src="data-ng-src="{image.Url}" />
// Other code
</div>
and in your controller, add something like that :
during init of the controller
$scope.mode = {};
//$scope.$watch('mode.isMultiple', function(newVal, oldVal){
// //insert your logic here
//});
$scope.mode.isMultiple = window.isMultiple;

Angular JS facebook like and ng-click

please am looking for a way to bind facebook like to my angularjs app, i already implemented easy app angularjs module, and everything is preety working fine.. how do i bind my ng click to the facebook like in such a way that it can only increase once and increment ones at the artistcontroller
<section ng-controller="MainCtrl">
<div class="row">
<div class="col-md-4 col-md-offset-4 text-center">
<div class="row">
<div>
<button class="btn btn-primary" ng-click="login()" ng-disabled="loginStatus.status == 'connected'">Connect with Facebook</button>
<button class="btn btn-danger " ng-click="logout()" ng-disabled="!loginStatus || loginStatus.status != 'connected'">Logout</button>
<!--<button class="btn btn-success" ng-click="share()">FB.ui</button>-->
</div>
<div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-search"></span></div>
<input type="text" ng-model="search" class="form-control" placeholder="FILTER">
</div>
</div>
</div>
</div>
<div class="row text-center">
<p class="contest-text"> Welcome, <span ng-show="me.name">{{ me.name }}!</span></p>
<span ng-show="me.name"><p class="contest-text">Vote For Your Favourite Goodnight Kiss Picture Below</p></span>
<p class="contest-text"><span ng-show="me.error">Please Login To Vote</span></p>
</div>
<div class="row" style="padding-top:20px;" ng-if="loginStatus.status == 'connected'">
<div class="col-md-3" ng-repeat="item in contestant | filter: search | orderBy:artistOrder:direction" style="margin-bottom:30px">
<div class="row text-center">
<p>
<img ng-src="uploads/{{item.ImageUrl}}" class="vote-img">
</p>
</div>
<div class="row ">
<div class="col-md-6 text-center">
<p class="contest-text">{{item.Name}}</p>
</div>
<div class="col-md-6 text-center">
<p class="contest-text"><span class="glyphicon glyphicon-thumbs-up"> {{item.Votes}} Votes </span></p>
</div>
</div>
<div class="row text-center">
<p class="contest-text voters"><a class="btn btn-warning" ng-click="upVote(item);"><b> VOTE</b></a> <button class="btn btn-success" ng-click="share()">SHARE</button></p>
</div>
</div>
</div>
<div class="row" style="padding-top:20px;" ng-if="!loginStatus || loginStatus.status != 'connected'">
<div class="col-md-3" ng-repeat="item in contestant | filter: search | orderBy:artistOrder:direction" style="margin-bottom:30px">
<div class="row text-center">
<p>
<img ng-src="uploads/{{item.ImageUrl}}" class="vote-img">
</p>
</div>
<div class="row ">
<div class="col-md-6 text-center">
<p class="contest-text">{{item.Name}}</p>
</div>
<div class="col-md-6 text-center">
<p class="contest-text"><span class="glyphicon glyphicon-thumbs-up"> {{item.Votes}} Votes </span></p>
</div>
</div>
<!-- <div class="row text-center">
<p class="contest-text voters"><b> Please Login To VOTE</b></p>
</div>-->
</div>
</div>
</div>
</section>
app.js controller code
var myApp = angular.module('votingApp', ['ezfb','ngRoute','artistController'])
.config(function (ezfbProvider) {
/**
* Basic setup
*
* https://github.com/pc035860/angular-easyfb#configuration
*/
ezfbProvider.setInitParams({
appId: 'xxxxxx'
});
})
.controller('MainCtrl', function($scope, ezfb, $window, $location, $q) {
updateMe();
updateLoginStatus()
.then(updateApiCall);
/**
* Subscribe to 'auth.statusChange' event to response to login/logout
*/
ezfb.Event.subscribe('auth.statusChange', function (statusRes) {
$scope.loginStatus = statusRes;
updateMe();
updateApiCall();
});
$scope.login = function () {
/**
* Calling FB.login with required permissions specified
* https://developers.facebook.com/docs/reference/javascript/FB.login/v2.0
*/
ezfb.login(null, {scope: 'email,user_likes'});
/**
* In the case you need to use the callback
*
* ezfb.login(function (res) {
* // Executes 1
* }, {scope: 'email,user_likes'})
* .then(function (res) {
* // Executes 2
* })
*
* Note that the `res` result is shared.
* Changing the `res` in 1 will also change the one in 2
*/
};
$scope.logout = function () {
/**
* Calling FB.logout
* https://developers.facebook.com/docs/reference/javascript/FB.logout
*/
ezfb.logout();
/**
* In the case you need to use the callback
*
* ezfb.logout(function (res) {
* // Executes 1
* })
* .then(function (res) {
* // Executes 2
* })
*/
};
$scope.share = function () {
var no = 1,
callback = function (res) {
console.log('FB.ui callback execution', no++);
console.log('response:', res);
};
ezfb.ui(
{
method: 'feed',
name: 'angular-easyfb API demo',
picture: 'http://plnkr.co/img/plunker.png',
link: 'http://plnkr.co/edit/qclqht?p=preview',
description: 'angular-easyfb is an AngularJS module wrapping Facebook SDK.' +
' Facebook integration in AngularJS made easy!' +
' Please try it and feel free to give feedbacks.'
},
callback
)
.then(callback);
};
/**
* For generating better looking JSON results
*/
var autoToJSON = ['loginStatus', 'apiRes'];
angular.forEach(autoToJSON, function (varName) {
$scope.$watch(varName, function (val) {
$scope[varName + 'JSON'] = JSON.stringify(val, null, 2);
}, true);
});
/**
* Update api('/me') result
*/
function updateMe () {
ezfb.getLoginStatus()
.then(function (res) {
// res: FB.getLoginStatus response
// https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus
return ezfb.api('/me');
})
.then(function (me) {
// me: FB.api('/me') response
// https://developers.facebook.com/docs/javascript/reference/FB.api
$scope.me = me;
});
}
/**
* Update loginStatus result
*/
function updateLoginStatus () {
return ezfb.getLoginStatus()
.then(function (res) {
// res: FB.getLoginStatus response
// https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus
$scope.loginStatus = res;
});
}
/**
* Update demostration api calls result
*/
function updateApiCall () {
return $q.all([
ezfb.api('/me'),
ezfb.api('/me/likes')
])
.then(function (resList) {
// Runs after both api calls are done
// resList[0]: FB.api('/me') response
// resList[1]: FB.api('/me/likes') response
$scope.apiRes = resList;
});
}
});
controller.js
var artistController = angular.module("artistController", []);
//artistController.directive("otcdynamic", function($compile){
// return{
// restrict: 'A',
// link: function(scope, element){
// var template = "<div class='selector'> <a class='btn btn-lg btn-warning' ng-click='upVote(item)'><b> VOTE</b></a></div>";
// var linkFn = $compile(template);
// var content = linkFn(scope);
// element.append(content);
// }
// }
//});
//artistController.factory('facebook', [function() {
// return FB;
//}]);
artistController.controller("LoginCtrl",['$scope',function($scope)
{
$scope.notAuthorized = true;
}]);
artistController.controller("ListController", ['$scope', '$http',function($scope, $http){
$http.get('ajax/getContestant.php').success(function(data){
$scope.contestant = data;
// $scope.artistOrder = 'name';
});
$scope.upVote = function(item){
item.Votes++;
updateVote(item.ID,item.Votes);
};
function updateVote(id,votes){
$http.post('ajax/updateVote.php?id='+id+'&votes='+votes);
}
}]);
artistController.controller("DetailsController", ['$scope', '$http','$routeParams',function($scope, $http,$routeParams){
$http.get('js/data.json').success(function(data){
$scope.artists = data;
$scope.whichItem = $routeParams.itemID;
if ($routeParams.itemID > 0) {
$scope.prevItem = Number($routeParams.itemID) -1;
}
else{
$scope.prevItem = $scope.artists.length -1;
}
if ($routeParams.itemID < $scope.artists.length -1) {
$scope.nextItem = Number($routeParams.itemID) +1;
}
else{
$scope.nextItem = 0;
}
});
}]);

ng-click ng-keypress passing form data not working

Im trying to send data from user input to display on the screen when button click.
The problem is that if i click on the button it simply passes to the next value without gathering the information and displaying in the screen. If i press ENTER it works how it should. i have searched all over internet several examples but simply couldnt get it to work. im using at the moment :
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
full html:
<div class="boxContent col-md-12">
<h1>{{lang.sec101.h1}}</h1>
<div class="col-md-12 lineBorder noPad" >
<div class="box1">
<p>
{{lang.sec101.title}}
</p>
</div>
<!-- dynamic form -->
<div class="col-md-12 borderBox boxLeft bg_box">
<form novalidate name="addForm">
<div class="boxLeft" ng-show="Question != ''">
<div ng-show="Question.infotip != 'yes'">
<h1 class="heading_left">{{Question.ask}}</h1>
</div>
<div ng-show="Question.infotip == 'yes'">
<h1 class="heading_left info">{{Question.ask}}
<span class="infotip yourData" tooltip-placement="top" tooltip-trigger="click" tooltip="{{Question.infotipText}}"></span>
</h1>
</div>
</div>
<div class="boxRight" ng-show="Question != ''">
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
</div>
<div class="boxRejestracjaInput">
<!-- <div id="legg-select" ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</div> -->
<div class="newSelect">
<label ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</label>
</div>
<input
ng-if="Question.type === 'text'"
type="{{Question.type}}"
name="institutionName"
class="inputName"
value="{{Question.value}}"
ng-model="value"
ng-minlength="{{Question.min}}"
ng-maxlength="{{Question.max}}"
ng-keypress="enter($event,value)"
placeholder="{{Question.placeholder}}"
ng-pattern="{{Question.pattern}}" />
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.minlength || addForm.institutionName.$error.maxlength">
Minimum {{Question.min}} znaków
</div> -->
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.maxlength">
Max {{Question.max}} znaków
</div> -->
<div class="custom-error institution" ng-show="addForm.institutionName.$error.pattern || addForm.institutionName.$error.maxlength || addForm.institutionName.$error.minlength">
{{Question.copy}}
</div>
</div>
</form>
</div>
<p>
{{lang.sec101.title2}}
</p>
<a href="rejestracja_10edit.html" class="btn btn-lg btn-default bt_edit" type="button">
{{lang.sec101.title3}}<span class="btn_bg_img"></span>
</a>
</div>
<div class="col-md-12 noPad" ng-repeat="sek in formOut">
<h3 class="daneHeading">{{sek.name}}</h3>
<div class="row">
<div class="col-md-12" >
<div class="col-md-4 col-sm-6 boxContent3 boxes" ng-repeat="row in sek.data">
<span class="leftBoxContrnt">{{row.shortAsk}}</h4></span>
<h4 class="rightBoxContrnt">{{row.value}}</h4>
</div>
</div>
</div>
</div>
<!-- <div class="row col-md-12" >
<h3 class="daneHeading">Hasło</h3>
</div>
<div class="row">
<div class="col-md-12 " >
<div class="col-md-4 col-sm-6 boxContent3">
<span class="leftBoxContrnt">Test</h4></span><span class="blueTxt"> *</span>
<h4 class="rightBoxContrnt">Test</h4>
</div>
</div>
</div> -->
</div>
my controller:
var app = angular.module('app', ['ngAnimate', 'ngCookies', 'ui.bootstrap', 'ngSanitize', 'nya.bootstrap.select', 'jackrabbitsgroup.angular-slider-directive']);
// var rej10_Controller = function($scope, $http, $cookieStore, $timeout, limitToFilter) {
app.controller('rej10_Controller', ['$scope', '$http', '$cookieStore', '$sce', '$timeout', 'limitToFilter',
function($scope, $http, $cookieStore, $sce, $timeout, limitToFilter) {
var view = 10,
arr,
data,
counterSection = 0,
counterAsk = 0;
$scope.opts = {};
$scope.slider_id = 'my-slider';
$scope.opts = {
'num_handles': 1,
'user_values': [0, 1],
'slider_min': 0,
'slider_max': 1,
'precision': 0,
};
/* language */
if (!$cookieStore.get('lang'))
$cookieStore.put('lang', 'pl');
var lang = $cookieStore.get('lang');
$scope.language = lang;
$scope.setLang = function(data) {
$cookieStore.put('lang', data);
$http.get('../widoki/json/lang/' + data + '/rej_' + view + '.json').
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn.sekcja[counterSection].data[counterAsk];
console.log($scope.lang);
}).
error(function(data, status, headers, config) {
console.log('error load json');
});
$scope.language = data;
};
/* get language pack */
$http({
method: 'GET',
url: '../widoki/json/lang/' + lang + '/rej_' + view + '.json'
}).
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
$scope.langLen = $scope.lang.formIn.length;
}).error(function(data, status, headers, config) {
console.log('error load json');
});
/* dynamic form */
$scope.enter = function(ev, d) {
if (ev.which == 13) {
$scope.addData(d);
}
};
$scope.addData = function(data) {
var newData = {};
/* latamy po id sekcji i po id pytania */
if (!$scope.formOut) {
$scope.formOut = [];
}
/* budowanie modelu danych wychodzcych */
newData = {
sekcja: counterSection,
name: $scope.lang.formIn[counterSection].name,
data: []
};
console.log(name);
if (!$scope.formOut[counterSection]) {
$scope.formOut.push(newData);
}
$scope.formOut[counterSection].data.push($scope.Question);
$scope.formOut[counterSection].data[counterAsk].value = data;
counterAsk++;
// zmieniamy sekcje
if (counterAsk == $scope.lang.formIn[counterSection].data.length) {
counterAsk = 0;
counterSection++;
}
if (counterSection == $scope.lang.formIn.length) {
$scope.Question = '';
/* zrobic ukrycie pola z formularza */
} else {
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
}
/* konwertowanie do jsona */
//var Json = angular.toJson($scope.formOut);
//console.log(Json);
};
$scope.submit = function() {
alert('form sent'); /* wysĹanie formularza */
};
$scope.getClass = function(b) {
return b.toString();
};
}
]);
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
app.config(['$tooltipProvider',
function($tooltipProvider) {
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave',
'show': 'hide'
});
}
]);
var ValidSubmit = ['$parse',
function($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if (form.$valid) {
fn(scope, {
$event: event
});
}
});
});
scope.$watch(function() {
return form.$valid
}, function(isValid) {
if (form.$submitted == false)
return;
if (isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
};
}
};
}
];
app.directive('validSubmit', ValidSubmit);
I cant figure out what is the problem.
Thanks in advance.
Try changing your ngClick button handler to an ngSubmit form handler and wiring that up. You didn't say what browser you're using, but most of them auto-submit forms on an ENTER keypress unless you trap it (which you aren't). Clicking a button won't do this.

Accessing parent $scope

I have posted earlier this post with the choice of not providing all my code. But now im stuck since with the same problem so I give it a change with providing all my code.
I know its not easy to debug when the code is huge so I will try to explain precisely the problem.
Actually the problem is described in my precedent post so please read it and look at the code that is a simplification of this one.
But basically the problem is : I want to access $scope.data.comments from the $scope.deleteComment() function
As you see the code below you will notice that I have to add ng-controller="CommentController" twice for this to work.
If someone could explain why.. that would be great but I guess that is another question.
Thanks in advance for your help.
MAIN HTML
<div ng-init="loadComments('${params.username}', '${params.urlname}' )" ng-controller="CommentController">
<div ng-repeat="comments in data.comments" >
<div sdcomment param="comments" ></div>
</div>
</div>
APP
var soundshareApp = angular.module('soundshareApp', ['ngCookies']);
DIRECTIVES
soundshareApp.directive('sdcomment', ['$cookies', function($cookies){
var discussionId = null;
var found = false;
var username = $cookies.soundshare_username;
return {
restrict:'A',
scope: {
commentData: '=param'
},
templateUrl: '/js/views/comment/templates/commentList.html',
link : function(scope, element, attrs, controller) {
scope.$watch(element.children(), function(){
var children = element.children();
for(var i=0; i<children.length; i++){
if(children[i].nodeType !== 8){ //pas un commentaire <!-- -->
if( !found ){
found = true;
discussionId == scope.commentData.discussionId
}else if(found && discussionId == scope.commentData.discussionId){
angular.element(children[i]).removeClass('message-content');
angular.element(children[i]).addClass('answer-message-content');
}
if(found && discussionId != scope.commentData.discussionId){
discussionId = scope.commentData.discussionId
}
if(username == scope.commentData.username){
element.parent().bind('mouseover', function() {
// $(".delete-comment-button").show()
element.parent().find("span.delete-comment-button:first").attr('style', 'display: block !important');
});
element.parent().bind('mouseleave', function() {
element.parent().find("span.delete-comment-button:first").attr('style', 'none: block !important');
});
}
}
}
});
}
}
}]);
TEMPLATE
<div class="message-wrapper" ng-controller="CommentController">
<div class='message-content' ng-click="state.show = !state.show; setUsername(commentData.username)">
<img class='message-vignette' ng-src='{{commentData.avatarUrl}}'/>
<div class='message-username'>{{commentData.username}}</div>
<div class='project-message'>{{commentData.comment}}</div>
<div class='message-date'>{{commentData.dateCreated | date:'dd.MM.yyyy # hh:mm:ss' }}</div>
<div class="clearfix"></div>
</div>
<div ng-repeat="answer in answers" class="answer-message-content" >
<div class='message-content' ng-click="state.show = !state.show">
<img class='message-vignette' ng-src='{{answer.avatarUrl}}'/>
<div class='message-username'>{{answer.username}}</div>
<div class='project-message'> {{answer.comment}}</div>
<div class='message-date'>{{answer.dateCreated | date:'MM/dd/yyyy # h:mma' }}</div>
<div class="clearfix"></div>
</div>
</div>
<div class="add-comment-content show-hide" ng-show="state.show" >
<img class='message-vignette answer-message-vignette' ng-src='{{commentData.currentUserAvatarUrl}}'>
<div class="">
<form ng-submit="addComment(commentData)" id="commentForm-{{commentData.projectId}}">
<input id="input-comment-{{commentData.projectId}}" type="text" maxlength="" autofocus="autofocus" name="comment" placeholder="Write a comment..." ng-model="commentData.msg">
<input type="hidden" name="discussionId" value="{{commentData.discussionId}}" >
<input type="hidden" name="projectId" value="{{commentData.projectId}}" >
</form>
</div>
</div>
<span ng-click="deleteComment(commentData)" class="btn btn-default btn-xs delete-comment-button"><i class="icon-trash"></i></span>
</div>
CONTROLLER
'use strict';
soundshareApp.controller('CommentController', function($scope, $http) {
$scope.data = { comments : [] }
$scope.answers = [];
$scope.state = {}
$scope.project = { id : [] }
$scope.username = null;
$scope.loadComments = function(userName, urlName){
$http({
url: '/comment/by_project_id',
method: "GET",
params:
{
username: userName,
urlname: urlName
}
}).success(function(data) {
$scope.data.comments = data;
console.log($scope.data.comments);//WORKING
});;
}
$scope.addComment = function(commentData){
if("undefined" != commentData.msg){
commentData.msg = "#" + $scope.username + ": " + commentData.msg;
$http({
method : "POST",
url : "/comment/addAnswer",
params:
{
comment: commentData.msg,
discussionId: commentData.discussionId,
projectId:commentData.projectId
}
}).success(function(data){
$scope.answers.push(data);
$('.show-hide').hide();
$scope.commentData.msg = '';
});
}
}
$scope.setUsername = function(username){
$scope.username = username;
}
$scope.deleteComment = function ( comment ) {
console.log($scope.data.comments);//NOT WORKING
};
});

Resources