I have to implement the share product functionality with the user after share i have to refresh the list here selectedSharedIntermediaryInAlbum is our array so how to implement this?
//refreshSharedIntermediary for refresh the lsit
$scope.refreshSharedIntermediary = function() {
$scope.selectedSharedIntermediaryInAlbum = $scope.selectedSharedIntermediaryInAlbum;
}
<div class="w3-right">
<button class="btn btn-rose btn-sm" tltle="refresh data" ng-click="refreshSharedIntermediary()">
<i class="glyphicon glyphicon-repeat"></i>
</button>
</div>
You can use $scope.reload function where need to reload the list ... i have used below concept :
<div class="well well-lg" ng-repeat="item in list track by item.id">
<button class="btn btn-default"
ng-click="collapsedFlags[item.id] = !collapsedFlags[item.id]">
{{ item.isCollapsed ? '+' : '-' }}
</button>
<div uib-collapse="collapsedFlags[item.id]" ng-bind="item.value"></div>
</div>
$scope.reload = function () {
$http.get('list.json').then(function (data) {
$scope.list = data && data.data || [];
});
};
$scope.collapsedFlags = {};
$scope.reload();
Working example : https://plnkr.co/edit/87vVb8Jjyz6yFGAjiHBK?p=preview
Related
I'm starting with AngularJS and I am using a controller variable to navigate an array of questions, and it is working when using nextQuestion function, index gets updated and the next question is shown in the view, but if I try to obtain the same value (index) in a different function, it always returns 0.
I have seen on other questions that you should use an object to contain the variable to not manipulate primitive types directly in the controller, but it still does not work.
My controller:
myApp.controller('SurveyController',['$scope','$http', '$location','$routeParams','surveyMetrics','DataService',function($scope,$http, $location,$routeParams,surveyMetrics,DataService){
console.log('LOADED QUIZ CONTROLLER');
var vm = this;
vm.scope = {
index: 0
};
vm.surveyMetrics = surveyMetrics;
vm.surveyQuestions = DataService.surveyQuestions;
vm.DataService = DataService;
/*
vm.getQuestions = function(){
$http.get('/api/questions').then(function(response){
$scope.questions = response.data;
});
}
*/
/*
vm.activateSurvey = function(){
surveyMetrics.changeState(true);
}
*/
vm.getCurrentIndex = function(){
return vm.scope.index;
}
vm.nextQuestion = function () {
console.log('NEXT QUESTION!');
console.log('NUMBER OF QUESTIONS: '+ vm.surveyQuestions.length);
var currentIndex = vm.getCurrentIndex();
var newIndex = currentIndex+1;
scope = {};
if (currentIndex == vm.surveyQuestions.length) {
newIndex = vm.surveyQuestions.length -1;
}
vm.scope.index = newIndex;
console.log('Inside Object: '+vm.scope)
console.log('vm.index'+vm.scope.index);
console.log('vm.indexFunction'+vm.getCurrentIndex());
}
/*
vm.previousQuestion = function () {
console.log('PREVIOUS QUESTION!');
console.log('NUMBER OF QUESTIONS: '+ vm.surveyQuestions.length);
if (vm.scope.index == 0) {
vm.scope.index = 0;
}else{
vm.scope.index--;
}
}
*/
vm.activeSurveyQuestion = function(questionId,index){
console.log('question id and index',questionId,index);
if (questionId == index) {
var navBtn = document.getElementById('navBtn_'+index);
navBtn.classList.add('active');
}
}
vm.navigateSurvey = function () {
var answerPane = document.getElementById('answer-pane');
document.onkeydown = function (e) {
console.log('INSIDE KEYDOWN: ')
e.preventDefault();
var pressedKey = e.keyCode;
console.log('PRESSED KEY IN SURVEY: ' + pressedKey);
if (pressedKey === rightArrow) {
console.log('survey - right arrow pressed');
document.getElementById('nextQuestionBtn').click();
console.log('FUCKING INDEX FML!: '+vm.getCurrentIndex()+' | '+vm.scope.index);
var questionType = DataService.getQuestionType(vm.scope.index);
console.log('Survey Controller: question type: '+questionType);
}
if (pressedKey === leftArrow) {
console.log('survey - left arrow pressed');
document.getElementById('previousQuestionBtn').click();
}
(...)
My View:
<!--Satisfaction Survey-->
<div ng-controller="SurveyController as survey" ng-init="survey.getSurvey();">
<!--
<p ng-repeat="question in survey.surveyQuestions" ng-show ="survey.surveyMetrics.surveyActive">
{{question.question}}
</p>
-->
<!--Survey Modal -->
<div class="modal fade" id="surveyModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="text-center"> Customer Satisfaction Survey</div>
<div class="modal-header">
<h4 class="modal-title">{{survey.surveyQuestions[survey.getCurrentIndex()].question}}</h4>
</div>
<div class="modal-body survey" id="answer-pane">
<div class="row">
<div class="col-sm-2 survey-left-arrow" ng-click="survey.previousQuestion();" id="previousQuestionBtn">
<p>‹</p>
</div>
<div class="col-sm-8">
<!-- <p ng-repeat="answer in survey.surveyQuestions[survey.index].answers">{{answer}}</p> -->
<p ng-repeat="answer in survey.surveyQuestions[survey.getCurrentIndex()].answers">
<button type="button" class="btn" id="answerId_{{survey.getCurrentIndex()}}"
ng-class="{'survey-check-box': (survey.surveyQuestions[survey.getCurrentIndex()].type !== 'SingleChoice'),
'survey-btn_{{($index+1)}}': (survey.surveyQuestions[survey.getCurrentIndex()].type === 'SingleChoice')}">
<input type="checkbox" ng-if="survey.surveyQuestions[survey.getCurrentIndex()].type !== 'SingleChoice'"> {{answer}}
</button>
</p>
</div>
<div class="col-sm-2 survey-right-arrow " ng-click="survey.nextQuestion();" id="nextQuestionBtn">
<p>›</p>
</div>
</div>
</div>
<div class="text-center">
<strong> <p>Question: {{survey.surveyQuestions[survey.scope.index].questionNum}} of {{survey.surveyQuestions.length}}</p> </strong>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<!-- <nav aria-label="Survey navigation">
<ul class="pagination pagination-sm justify-content-center">
<div ng-repeat="question in survey.surveyQuestions" >
<li class="page-item">
<a class="page-link" id = "navBtn_$index" ng-click="survey.index = $index">{{question.id}}</a>
</li>
</div>
</ul>
</nav> -->
</div>
</div>
I would like for the controller to change the variable and the view to update accordingly
Thank you for your time and thank you in advance.
It's 'survey.scope.index' not 'survey.index' in your HTML. I think you may be unclear the difference between using 'this' and '$scope'. You're mixing the two together which is not necessary. I would suggest removing 'scope' and just reference it in your HTML as 'survey.index'.
I have a simple AngularJS app that shows a table with data on an ng-repeat after the user logins. I'm having an issue where after logging in, the table briefly shows blank rows and then the actual rows with data. Any suggestions on how to fix this?
This is the controller for the login:
$scope.login = function(user) {
loginSrvc.login(user).then(function(response) {
if (response == "authentication failed") {
$scope.error = true;
$scope.user = {};
$location.path("/");
} else {
if (response.group_name == "On Site Registration"){
var data = {
event: response.zk_event_id,
group: response.zk_group_id
};
$scope.getAvailableCamper(data);
}
else if (!response.zk_group_id) {
$location.path("/form/" + response.zkp_camper_id);
}
else {
$location.path("/dashboard/" + response.zk_event_id + "/" + response.zk_group_id);
}
}
})
}
$scope.getAvailableCamper = function(data) {
dashboardSrvc.fetchGroup(data).then(function(response){
var findAvailableCamper = _.find(response.data, {status: null});
console.log("this is find", findAvailableCamper);
var id = findAvailableCamper.zkp_camper_id;
$location.path("/onSiteForm/" + id);
})
}
This is the controller for the table:
$scope.campers = function() {
$scope.camper = loginSrvc.getCampers();
}
$scope.campers();
$scope.fetchCampers = function(id) {
dashboardSrvc.fetchCampers(id).then(function(response){
$location.path("/form/" + id);
})
}
Here's the html code for table:
<tr ng-repeat="campers in camper">
<td>{{$index + 1}}</td>
<td>{{campers.name_first}}</td>
<td>{{campers.name_last}}</td>
<td><button type="submit" name="submit" ng-click="register(campers)" class="btn btn-success" role="button" ng-hide="campers.status == 'Submitted' " ng-disabled="!(!!campers.name_first && !!campers.name_last && !!campers.gender && !!campers.city && !!campers.date_of_birth && !!campers.email && !!campers.emergency_cell_phone && !!campers.emergency_contact_first_name && !!campers.emergency_contact_last_name && !!campers.emergency_home_phone && !!campers.relationship_to_camper && !!campers.first_time_flag )">Submit</button> <p ng-show ="campers.status == 'Submitted'" > {{campers.registration_date | date: 'medium'}}
</p>
</td>
<td>{{campers.status}}</td>
<td>
<button ng-click="fetchCampers(campers.zkp_camper_id)" type="submit" name="view" class="btn btn-default" role="button" ng-show="campers.status == 'Submitted' "><span class="glyphicon glyphicon-eye-open"></span></button>
<button ng-click="fetchCampers(campers.zkp_camper_id)" type="submit" name="edit" class="btn btn-default" role="button" ng-hide="campers.status == 'Submitted' " ><span class="glyphicon glyphicon-edit"></span></button>
<button type="button" ng-click="setValue(campers.zkp_camper_id)" name="deleteModalLauncher" id="deleteModalLauncher" class="btn btn-danger" role="button" data-toggle="modal" data-target="#deleteModal" ng-hide="campers.status == 'Submitted' " ><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
</td>
</tr>
I really appreciate the help! Thanks!
There is a directive to minimize flickering that angular loop does while check bindings and all. it is called ng-cloak and it can be added to any element on your view.
More info : https://www.w3schools.com/angular/ng_ng-cloak.asp
...
You can also use angularjs event who is fired when content is fully loaded and set a flag ex. loaded = true and then use ng-show with loaded variable.
Controller :
$scope.$on('$viewContentLoaded', function(){
$scope.loaded = true;
});
View :
<table ng-show="loaded">
.....
</table>
Hope that helps!
I am having issue with the product list quantity buttons. I am new to angular js and trying to build product list which is having quantity increase and decrease button. I have build the list with ng-repeat, for increase and decrease button i am calling a function qty_incr() and qty_decr() it works but reflecting on every list item. I want to reflect only the same product. The same thing with jquery can done like this
$('.qty_incr').click(function(){
$(this).parents('.cart_product').children('#incr_decr_no').text(parseInt($(this).parents('.cart_product').children('#incr_decr_no').text() + 1));
})
Wondering how could same can achieve with angularjs, here is my code
<p ng-show="loading" class="loading"><img src="assets/img/Spinner-1s-200px.gif" width="50" /></p>
<div class="cart_products" ng-hide="loading" ng-repeat="product in data.products">
<div class="cart_product">
<div class="cart_pro_img"><img src="{{product.product_image}}" /></div>
<div class="cart_pro_detail">
<div class="cart_pro_title">{{product.product_name}}</div>
<div class="cart_pro_price">₹ {{product.price}}</div>
<div class="cart_pro_incr_decr">
<i class="fa fa-minus-circle" ng-click="qty_decr($parent.item)" style="color:#FF4646"></i>
<span id="incr_decr_no" ng-init="$parent.item.quantity=1">{{item.quantity}}</span>
<i class="fa fa-plus-circle" ng-click="qty_incr()" style="color:#68C549"></i>
<i class="fa fa-times-circle-o" {{item.product_id}}></i>
</div>
</div>
</div>
JS
app.controller("cart", function($scope, $http){
var guestid = localStorage.getItem('guestid');
$scope.loading = true;
$http.get(baseurl+"webservice.php?req=cartproducts&guestid="+guestid)
.then(function(response){
$scope.loading = false;
$scope.data = response.data;
//console.log($scope.data);
//$rootScope.cartcount(guestid);
});
$scope.qty_incr = function(item){
$scope.item.quantity = $scope.item.quantity + 1;
}
$scope.qty_decr = function(item){
if($scope.item.quantity > 1){
$scope.item.quantity = $scope.item.quantity - 1;
}
}
})
I have solved it by modifying the html and js code
My HTML
<div class="cart_products" ng-hide="loading" ng-repeat="product in data.products">
<div class="cart_product">
<div class="cart_pro_img"><img src="{{product.product_image}}" /></div>
<div class="cart_pro_detail">
<div class="cart_pro_title">{{product.product_name}}</div>
<div class="cart_pro_price">₹ {{product.price}}</div>
<div class="cart_pro_incr_decr">
<i class="fa fa-minus-circle" ng-click="qty_decr(item)" style="color:#FF4646"></i>
<span id="incr_decr_no" ng-init="item.quantity=1">{{item.quantity}}</span>
<i class="fa fa-plus-circle" ng-click="qty_incr(item)" style="color:#68C549"></i>
<i class="fa fa-times-circle-o" ng-click="removefromcart(product.product_id)"></i>
</div>
</div>
</div>
and JS is:
app.controller("cart", function($scope,$rootScope, $http){
var guestid = localStorage.getItem('guestid');
$http.get(baseurl+"webservice.php?req=cartproducts&guestid="+guestid)
.then(function(response){
$scope.data = response.data;
console.log($scope.data);
})
$scope.qty_incr = function(item){
item.quantity = item.quantity + 1;
}
$scope.qty_decr = function(item){
if(item.quantity > 1){
item.quantity = item.quantity - 1;
}
}
})
I have a factory.all() function that gets called on page load. However, whenever I enter a new entry into my MongoDB or delete one, it is not refreshing. I am logging (data) to console to see how many objects are returned. Currently, I have four being returned. Even when I delete one of them, and refresh the page, 4 objects are still logged to the console. Is this a Browser caching issue? Is there a way to counter this?
My controller:
angular.module('quizCtrl', [])
.controller('quizController', function(Quiz) {
// Assign local variable to be used in application
var vm = this;
// To Load All Quizzes on Application
Quiz.all().success(function(data) {
console.log(data);
});
My Factory:
angular.module('quizService', [])
.factory('Quiz', function($http) {
// create a new object
var quizFactory = {};
// get a single quiz
quizFactory.get = function(id) {
return $http.get('/api/quiz/' + id);
};
// get all quizzes
quizFactory.all = function() {
return $http.get('/api/quiz/');
};
// create a quiz
quizFactory.create = function(quizData) {
return $http.post('/api/quiz/', quizData);
};
// update a quiz
quizFactory.update = function(id, quizData) {
return $http.put('/api/quiz/' + id, quizData);
};
// delete a quiz
quizFactory.delete = function(id) {
return $http.delete('/api/quiz/' + id);
};
// return our entire quizFactory object
return quizFactory;
});
Endpoint:
// GET request to load ALL quiz at once
apiRouter.route('/quiz')
.get(function(req, res) {
Quiz.find({}, function(err, quiz) {
if (err) res.json({ message: "Error: " + err})
res.json(quiz);
});
});
// GET request to get a specific quiz only
apiRouter.route('/quiz/:quiz_id')
// get the user with that id
.get(function(req, res) {
Quiz.findById(req.params.quiz_id, function(err, quiz) {
if (err) res.json("Error: " + err);
// return that user
res.json(quiz);
});
});
HTML Displaying Data
<div class="panel panel-success" ng-show="quiz.quiz">
<div class="panel-heading">
<div class="panel-title">{{ quiz.quiz.question }}
<div style="float:right">
{{ ex.createdAt | date : "MMM d, y h:mm a" }}
</div>
</div>
</div>
<div class="panel-body">
<button type="button" class="btn btn-default" ng-click="quiz.submitAnswer(quiz.quiz.answers[0], quiz.quiz._id, quiz.quiz.correctAnswer)" ng-disabled="quiz.isDisabled">A. {{ quiz.quiz.answers[0] }}</button><br><br>
<button type="button" class="btn btn-default" ng-click="quiz.submitAnswer(quiz.quiz.answers[1], quiz.quiz._id, quiz.quiz.correctAnswer)"" ng-disabled="quiz.isDisabled">B. {{ quiz.quiz.answers[1] }}</button><br><br>
<button type="button" class="btn btn-default" ng-click="quiz.submitAnswer(quiz.quiz.answers[2], quiz.quiz._id, quiz.quiz.correctAnswer)" ng-disabled="quiz.isDisabled">C. {{ quiz.quiz.answers[2] }}</button><br><br>
<button type="button" class="btn btn-default" ng-click="quiz.submitAnswer(quiz.quiz.answers[3], quiz.quiz._id, quiz.quiz.correctAnswer)"" ng-disabled="quiz.isDisabled">D. {{ quiz.quiz.answers[3] }}</button><br><br>
<div class="alert alert-info" role="alert" ng-if="(quiz.successMessage)">
<strong>{{ quiz.successMessage }}</strong> is correct.
</div>
<div class="alert alert-danger" role="alert" ng-if="(quiz.failureMessage)">
<strong>{{ quiz.failureMessage }}</strong> is incorrect.
</div>
<div class="alert alert-success" role="alert" ng-if="(quiz.correctMessage)">
Correct answer is: <strong>{{ quiz.correctMessage }}</strong>
</div>
Correct So Far: {{ quiz.correctSoFar }}
</div>
<div class="panel-body">
<div class="panel-body">Posted by: {{ exam.postedBy }}</div>
<div style="float:right">
<button class="btn btn-success" type="button" ng-click="quiz.nextQuestion()" ng-if="quiz.isDisabled">Next</button>
</div>
</div>
</div>
</div>
I am working with angular js for my dashboard. I have an over all minimize button to minimize all widget and then each widget have own minimize button. I done with following script its not working.
when i click widget minimize button its minimize all widget. but i want minimize that widget only.
var dashboard = angular.module("dashboard",['ui.bootstrap']);
dashboard.controller('dash-control', ['$scope', function($scope) {
$scope.isHidden = false;
$scope.toggle = function(){
$scope.isHidden = !$scope.isHidden;
};
$scope.toggleonce= function()
{
if( this.isHidden === true)
this.isHidden = false;
else
this.isHidden = true;
};
}]);
HTML code like follow:
<div class="contentpanel" ng-app="dashboard" ng-controller="dash-control as ctrl">
<button class="btn btn-white" type="button" ng-click="toggle()"><i class="fa fa-minus-square"> </i> </button>
<div>
<i class="fa fa-minus"></i>
<div class="row tinychart" ng-show="isHidden">Contenr Heading 1</div>
<div class="row tinychart" ng-hide="isHidden">Content Description 1</div>
</div>
<div>
<i class="fa fa-minus"></i>
<div class="row tinychart" ng-show="isHidden">Contenr Heading 2</div>
<div class="row tinychart" ng-hide="isHidden">Content Description 1</div>
</div>
......
.....
.....
</div>
I would rather create a directive with isolated scope for represent a inner widget. for instance;
dashboard.directive('myWidget',function(){
return {
scope:{},
template:"<div>\r\n<a href=\"\" class=\"tooltips\" ng-click=\"toggleonce()\" title=\"Minimize Panel\"><i class=\"fa fa-minus\"><\/i><\/a>\r\n<div class=\"row tinychart\" ng-show=\"isHidden\">asdasdasd<\/div>\r\n<div class=\"row tinychart\" ng-hide=\"isHidden\">sdasdasd<\/div>\r\n\r\n <\/div>",
link:function($scope)
{
$scope.isHidden = false;
$scope.toggle = function(){
$scope.isHidden = !$scope.isHidden;
};
$scope.togglesingle = function()
{
if( this.isHidden === true)
this.isHidden = false;
else
this.isHidden = true;
};
}
}
});
Then In Html Body;
<div class="contentpanel" ng-app="dashboard" >
<button class="btn btn-white" type="button" ng-click="toggle()"><i class="fa fa-minus-square"> </i> </button>
<div my-widget></div>
<div my-widget></div>
</div>
Note that I haven't run and check the example. I hope you got the idea.
Edited:
The ng-repeat will loop the array (list) and initiate each element to 'item' variable. You can pass that data to your directive. Check the updated code.