AngularJS refresh view after send comment - angularjs

I created controller in AngularJS to display and send comment to my rest endpiont. How to refresh comment list after user click and send comment?
My controller:
.controller('CommentController',
function($scope, $routeParams, NewsModel){
var newsId = $routeParams.id;
path = 'getCommetnsByNewsId/'+newsId;
var comm = this;
var data = new Date().toLocaleString();
$scope.createComm = function(comment){
NewsModel.createComment(angular.extend({},
{data: data, newsId: newsId}, comment)).then(function (result){
initCreateComm();
})
}
function initCreateComm(){
comm.newComm = { comment: '', author: ''};
}
NewsModel.getCommentById().then(function (result){
$scope.comments = result.data;
console.log($scope.comments);
});
})
Service:
.service('NewsModel', function($http, ENDPOINT_URI){
var service = this;
function getUrl(){
return ENDPOINT_URI + path;
}
service.all = function(){
return $http.get(getUrl());
}
service.getCommentById = function(){
return $http.get(getUrl());
}
service.createComment = function(comment){
return $http.post(getUrl(),comment);
}
});
And HTML:
<!-- Comments Form -->
<div class="well">
<h4>Leave comment:</h4>
<form role="form" ng-submit="createComm(newComment)">
<div class="form-group">
<input type="text" class="form-control" ng-model="newComment.author" placeholder="Autor">
</div>
<div class="form-group">
<textarea class="form-control" ng-model="newComment.comment" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Wyƛlij</button>
</form>
</div>
<hr>
<div ng-repeat="comm in comments">
<div class="media">
<div class="media-body">
<h4 class="media-heading">{{comm.author}}
<small>{{comm.data}}</small>
</h4>
{{comm.comment}}
</div>
</div>
</div>
</div>
How to do this?

This is how you get the comments:
NewsModel.getCommentById().then(function (result){
$scope.comments = result.data;
console.log($scope.comments);
});
So you need to wrap it in a function and call it after adding a new comment:
$scope.getComments = function() {
NewsModel.getCommentById().then(function (result){
$scope.comments = result.data;
console.log($scope.comments);
});
};
$scope.getComments(); // Init the comments as the controller loades
And add this at the end of $scope.createComm = function(comment){:
$scope.createComm = function(comment){
NewsModel.createComment(angular.extend({},
{data: data, newsId: newsId}, comment)).then(function (result){
initCreateComm();
$scope.getComments(); // Update comments
})
}

Simply call your server to retrieve all the comments when you need to refresh comments list.
function fetchComments(){
NewsModel.all().then(function(res){
$scope.comments = res;
});
}
and then call fetchComments() whenever you want to update the comments.

Related

Laravel - pass form input from angular to API controller?

I have a delete controller in my backend that is done in angular. Its angular controller looks like this:
angular.module('dashboard')
.controller('CoursesDeleteController', ['$scope', '$http', '$location', '$routeParams', function ($scope, $http, $location, $routeParams) {
$scope.id = $routeParams.id;
$scope.courses = {
delete: 0
};
$scope.loaded = false;
$scope.busy = false;
$scope.error = false;
$scope.setDelete = function (value) {
$scope.webinarcourses.delete = value;
};
$scope.delete = function () {
$scope.busy = true;
$http.delete('/api/courses/' + $scope.courses.id, $scope.courses).then(function (response) {
$scope.busy = false;
$location.path('/courses');
}, function (response) {
$scope.busy = false;
$scope.error = 'Unable to delete course...';
});
};
var load = function () {
$scope.busy = true;
$http.get('/api/courses/' + $scope.id).then(function (response) {
$scope.courses = response.data;
$scope.busy = false;
$scope.loaded = true;
}, function () {
$scope.busy = false;
$scope.error = 'Unable to load course...';
});
};
load();
}]);
The view is
<form role="form" class="panel-footer">
<div class="form-group col-xs-12 col-sm-6 col-md-2">
<label>Delete from Integrations?</label><br>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-info"
ng-class="{ active: courses.delete == 1 }"
ng-click="setDelete(1)">
<input type="radio"> Yes
</label>
<label class="btn btn-info"
ng-class="{ active: courses.delete == 0 }"
ng-click="setDelete(0)">
<input type="radio"> No
</label>
</div>
</div>
<button class="btn btn-danger" ng-click="delete()" ng-disabled="busy || !loaded"><span class="glyphicon glyphicon-trash"></span> Delete</button>
<span class="glyphicon glyphicon-arrow-left"></span> Back
<div class="progress progress-striped active push-sm" ng-show="busy">
<div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
<span class="sr-only">Busy...</span>
</div>
</div>
</form>
Then in my API controller:
public function destroy($id)
{
$data=Input::all(); // do something with this data...
\App\Courses::find($id)->delete();
}
The problem is I am not seeing any data. I thought I would have courses.delete available via Input:: but it is null.
I must be overlooking something and maybe it has to do with the fact that the Courses model does not have a delete column, but I thought it wouldn't matter if I am just passing from angular to the API controller and not actually trying to access a non existent column. I am just trying to use courses.delete as a way to determine some actions in the delete method of the API controller.
Ok, I overlooked the peculiarities of the delete method. Turns out I just needed to do do this:
$http.delete('/api/courses/' + $scope.courses.id, {
params: {delete: $scope.courses.delete}
}).then(function (response) {
regards

Using AngularJS, how can I pass a clicked object property to a function?

Using AngularJS, I am creating a wizard. In order to navigate properly, the clicked wizardresult.Title needs to be passed into the function showpagetwo().
Here is the HTML:
<div ng-app="wizardApp">
<div ng-controller="MainCtrl">
<div ng-repeat="wizardresult in wizardresults">
<div id="initial" ng-if="wizardresult.RootItem =='Yes'">
<button type="button" class="btn btn-primary" ng-click="showpagetwo()">{{wizardresult.Title}}
...
</button>
</div>
<div id="pagetwo" style="display:none">
...
</div>
</div>
</div>
</div>
My JS:
function showpagetwo(){
console.log("Hello");
$("#pagetwo").fadeIn();
$( "#initial" ).hide()
}
var app = angular.module('wizardApp', []);
app.controller('MainCtrl', function($scope, $http, $q){
var supportList;
$(document).ready(function() {
$scope.getSupportList();
});
$scope.prepContext = function(url,listname,query){
var path = url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query;
return path;
}
$scope.getSupportList = function() {
supportList = $http({
method: 'GET',
url: this.prepContext(siteOrigin+"/divisions/testing","SupportList","?$orderBy=Title"),
headers: {
"Accept": "application/json; odata=verbose"
}
}).then(function(data) {
//$("#articleSection").fadeIn(2000);
console.log(data.data.d.results);
$scope.wizardresults = data.data.d.results;
});
};
});
I have tried ng-click="showpagetwo(wizardresult.Title)" and just ng-click="showpagetwo()"but the function is not firing at all either way.
What is my issue here?
You just need to put your callback function in the $scope and pass the argument you want to receive.
Something like this:
HTML:
<div class="test" ng-controller="Ctrl">
<button ng-click="myFn(wizardresult.Title);">click me</button>
<div>
JS:
var app = angular.module('app', []);
function Ctrl($scope) {
$scope.wizardresult = {Title: 'myname'};
$scope.myFn = function(param){
alert("Param: " + param);
};
}
Check this jsfiddle: http://jsfiddle.net/m1q4q4cm/
Add the function showpagetwo() inside controller.
var app = angular.module('wizardApp', []);
app.controller('MainCtrl', function($scope, $http, $q){
var supportList;
$(document).ready(function() {
$scope.getSupportList();
});
$scope.prepContext = function(url,listname,query){
var path = url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query;
return path;
}
$scope.showpagetwo= function(title){
console.log("Hello "+title);
$("#pagetwo").fadeIn();
$( "#initial" ).hide()
}
$scope.getSupportList = function() {
supportList = $http({
method: 'GET',
url: this.prepContext(siteOrigin+"/divisions/testing","SupportList","?$orderBy=Title"),
headers: {
"Accept": "application/json; odata=verbose"
}
}).then(function(data) {
//$("#articleSection").fadeIn(2000);
console.log(data.data.d.results);
$scope.wizardresults = data.data.d.results;
});
};
});
You cannot call a function outside your app directly with ng-click. The angular way of what you are trying to achieve will be like
Html
<div ng-app="wizardApp">
<div ng-controller="MainCtrl">
<div ng-repeat="wizardresult in wizardresults">
<div id="initial" ng-if="wizardresult.RootItem =='Yes'" ng-show="showThisDiv">
<button type="button" class="btn btn-primary" ng-click="showpagetwo(wizardresult.Title)">{{wizardresult.Title}}
...
</button>
</div>
<div id="pagetwo" ng-hide="showThisDiv">
...
</div>
</div>
</div>
</div>
Controller
app.controller('MainCtrl', function($scope, $http, $q){
$scope.showThisDiv = true
$scope.showpagetwo = function(wizardTitle){
$scope.showThisDiv = true
}
});
For the animation effects, you can use angular-animate library and add class="animate-show animate-hide" to divs for the fade effects.
For some reason if you want to use jquery, then just change the scope function to
$scope.showpagetwo = function(wizardTitle){
$("#pagetwo").fadeIn();
$( "#initial" ).hide()
}
Hope this will help.

ng-model data not getting when saving the data

here save the ng-model is newattendance saving to database. "newattendance._id" is not taken as a ng-model.how to make it "newattendance._id" is ng-model
<select class="form-control" ng-options="item.empcode as item.empcode for item in totemplist" ng-model="item.empcode">
</select>
<input type="text" ng-repeat="newattendance in totemplist" ng-model="newattendance._id" ng-show="item.empcode ==newattendance.empcode" style="width:200px;" ><br>
<input placeholder="Enter Attendacne Date" ng-model="newattendance.doa">
<button class="btn btn-primary" ng-click="checkOut()">checkOut</button>
Controller
EmpMasterController.controller("AttendanceController", ['$scope', 'AttendanceFactory',"EmpAddService", function($scope, AttendanceFactory,EmpAddService){
$scope.newattendance={};
$scope.totemplist=EmpAddService.getAllEmpAddItems();
console.log($scope.totemplist);
$scope.checkIn = function(){
AttendanceFactory.addAttendance($scope.newattendance);
$scope.newattendance = {}
}
$scope.getAllAttendance = function(){
console.log("$$$$$"+$scope.newattendance._id)
$scope.attendancedetails =AttendanceFactory.getAllAttendance($scope.newattendance._id);
}
}])
Factory
EmpFactModule.factory("AttendanceFactory", function($resource, RES_URL){
var attendanceResource = $resource(RES_URL+"attandence/:id/:attid",
{"id": "#id", "attid": "#attid"}, {update: {method: "PUT"}})
var attendanceDetails;
return {
addAttendance: function(newattendance){
console.log("..1.. " + newattendance._id)
attendanceResource.save({"id":newattendance._id}, newattendance, function(data){
console.log("Add Success ")
}, function(data, status){
console.log("Add Failed*****");
})
},
getAllAttendance: function(_id){
console.log("..#.. " + _id)
attendanceDetails = attendanceResource.query({"id": _id});
return attendanceDetails;
},
}
})
please help me how make it as ng-model and how to save this...
I've create a JSFiddle for you which hopefully will help you understand the 2 way binding in angular.
you dont need to pass the newattendance object to the check-out function, it is already saved on the scope.
HTML:
<div ng-app="app">
<div ng-controller="formValidation">
<div>
<div>
<span>User Name</span>
<input type="text" placeholder="John" ng-model="newattendance._id">
<span>
<button ng-click="submit()">
check out
</button>
</span>
</div>
</div>
<pre>{{newattendance._id}}</pre>
</div>
</div>
JS:
var app = angular.module('app', []);
app.controller('formValidation', function($scope) {
$scope.submit=function(){
var formPost = {
"Username":$scope.newattendance._id
};
console.log(formPost);
}
});

Angular ui-select2 values not being detected in scope

For a bit of background, I am trying to create a simple form that will allow a user to send a message. I am using ui-select2 to allow the user to search for the message recipient, but for some reason selecting the user doesn't update the necessary scope variable.
<div ng-show="message_page == 'Compose'" ng-controller="userctrl" class="col-sm-9">
<section class="panel">
<header class="panel-heading wht-bg">
<h4 class="gen-case"> Compose Mail
<form action="#" class="pull-right mail-src-position">
</form>
</h4>
</header>
<div class="panel-body">
<div class="compose-mail">
<form role="form-horizontal" method="post">
<div class="form-group">
<label for="to" class="">To:</label>
<select style="min-width:150px" ui-select2 ng-model="message.recipient" data-placeholder="Who do you want to message?">
<option ng-repeat="user in users" value="user.id">{{user.name}}</option>
</select>
{{message}}
</div>
<div class="form-group">
<label for="subject" class="">Subject:</label>
<input ng-model="message.subject" type="text" tabindex="1" id="subject" class="form-control">
</div>
<div class="compose-editor">
<textarea ng-model="message.content" class="wysihtml5 form-control" rows="9"></textarea>
</div>
<div class="compose-btn">
<button ng-click="send()" class="btn btn-primary btn-sm" onclick="$('#cc').parent().addClass('hidden'); $('#cc').focus();"><i class="fa fa-check"></i> Send</button>
</div>
</form>
</div>
</div>
</section>
</div>
</div>
This is the relevant html code (which is a template for a directive) and here is the directive code:
.directive('messageslist', function(){
return{
templateUrl: 'message-list-template.html',
restrict: 'E',
controller: function(Auth, $scope, $rootScope, $timeout, ListMessagesSvc, SingleMessageSvc, MessageCreateSvc){
$scope.message = {};
var messagesLoader = function(){
ListMessagesSvc.query().$promise.then(function(data){
$rootScope.messages = $scope.messages = data;
var unread_messages_count = 0;
for(var i = 0; i < $scope.messages.length; i++){
if($scope.messages[i].type == "unread"){
unread_messages_count++;
}
}
console.log("There are " + unread_messages_count + " unread messages");
$rootScope.unread_messages_count = $scope.unread_messages_count = unread_messages_count;
})
}
$scope.refresh_messages = function(){
if(Auth.isAuthenticated()){
messagesLoader();
}
}
$scope.open_message = function(message_id){
console.log("The message is being opened" + message_id);
SingleMessageSvc.get({id: message_id}).$promise.then(function(data){
$scope.current_message = data;
})
$scope.message_page = "Single";
}
$scope.inbox = function(){
if(Auth.isAuthenticated()){
messagesLoader();
}
$scope.message_page = "Inbox";
}
$scope.compose = function(){
$scope.message_page = "Compose";
}
$scope.send = function(){
console.log($scope.message);
MessageCreateSvc.save($scope.message).$promise.then(function(data){
$scope.message = null;
$scope.message_page = "Inbox";
});
}
$scope.discard = function(){
$scope.message = null;
$scope.message_page = "Inbox";
}
var infiniteLoop = function(){
$timeout(function(){
if(Auth.isAuthenticated()){
messagesLoader();
}
infiniteLoop();
}, 60000);
}
if(Auth.isAuthenticated()){
messagesLoader();
}
infiniteLoop();
$scope.message_page = "Inbox";
}
}
})
I have tried the directive both with and without the link element and the scope element, but these changes didn't seem to make any difference. I have also attempted to output the contents of the message object, and while it does pick up changes to the content and the topic it doesn't pick up changes to the recipient. Also, I have successfully used ui-select2 elsewhere in my application so I am not sure what it different about this instance.
Let me know if you need any more information.
You have to change this:
value="user.id"
to this:
value="{{user.id}}"
or this:
ng-value="user.id"
Otherwise all the values will be 'user.id'
For anyone with a similar issue to myself, try removing the controller element. Fixed the issue for me!

Why won't my view template bind to a scope variable with AngularJS?

My view is:
<div class="container" ng-controller="MyController">
<div class="row">
<div class="col-md-8">
<textarea class="form-control" rows="10" ng-model="myWords" ng-change="parseLanguage()"></textarea>
</div>
<div class="col-md-4" ng-show="sourceLanguage !== null">
Language: {{ sourceLanguage }}
</div>
</div>
</div>
My controller is:
webApp.controller('MyController', [
'$scope', '$rootScope', 'TranslateService', function($scope, $rootScope, CodeService) {
$scope.init = function() {
return $scope.sourceLanguage = null;
};
$scope.parseLanguage = function() {
return TranslateService.detectLanguage($scope.myWords).then(function(response) {
console.log($scope.sourceLanguage);
$scope.sourceLanguage = response.data.sourceLanguage;
return console.log($scope.sourceLanguage);
});
};
return $scope.init();
}
]);
The console logs show the right data. But in the view, sourceLanguage never updates. Why would this be?
In case the promise you are evaluating is not part of the Angular context you need to use $scope.$apply:
$scope.parseLanguage = function() {
TranslateService.detectLanguage($scope.myWords).then(function(response) {
$scope.$apply(function() {
$scope.sourceLanguage = response.data.sourceLanguage;
});
});
};

Resources