how to create “fill in the blank” questions using angularJS [closed] - angularjs

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am very new to the technologies and learning angular js by developing a quiz app using angularJS. I want to mix the questions of Multiple choice questions and fill in the blank questions. I have created multiple choice questions but I am not able to create fill in the blank questions. could someone please give some suggestions, how to create fill in the blank questions.
for example: how ---you?, what --- you doing?. these kinds of questions.
here is my code:
questions.html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="questionsController" ng-init="StartTimer()">
<div id="test_status" style="text-align:left">
<h3 ng-show='ques'>Question {{pos+1}} of {{questions.length}}</h3>
<h3 ng-hide='ques'>Test Completed </h3>
</div>
<ol style="list-style-type:none">
<li id="test" colspan="3">
<div ng-show="ques">
<h3>{{question}}</h3>
<input type='radio' name='choices' value='A'>{{chA}}
<br>
<input type='radio' name='choices' value='B'>{{chB}}
<br>
<input type='radio' name='choices' value='C'>{{chC}}
<br>
<br>
<button ng-click='checkAnswer()'>Next</button>
</div>
</li>
</ol>
<div ng-hide='ques'>
<div class="col-lg-5">
<div class="panel panel-danger">
<div class="panel-heading">Score Card</div>
<div class="panel-body">
<h3>You have got {{correct}} correct of {{questions.length}} questions</h3>
<h4>Exam Finished in Time :{{minuteleft}} Minutes {{sec}} Seconds</h4>
<div ng-controller="resultController">
<button ng-click='click()' class="btn btn-success">Continue</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-2">
<div class="panel panel-primary">
<div class="panel-heading">Time Limit</div>
<div class="panel-body">
<h2>{{min}}:{{sec}}</h2>
</div>
</div>
</div>
<br>
</div>
</body>
and main.js
var myApp = angular.module('myApp',['ngRoute']);
myApp.controller('questionsController', function($scope,$interval,$filter,$http) {
$scope.pos = 0, $scope.correct = 0, $scope.ques = true;
$scope.questions = [
["Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C"],
["Which of the following is an interface ?", "Thread", "Date", "Calender", "A"],
["Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A"],
["What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C"],
["What is the default value of Java datatype boolean?", "true", "false", "0", "A"]
];
$scope.totalsecoriginal = $scope.totalsec = 60;
$scope.totalsec--;
$scope.min = parseInt($scope.totalsec / 60, 10);
$scope.sec = $scope.totalsec - ($scope.min * 60);
$scope.date = new Date();
$scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');
$scope.currentTime = new Date();
$scope.currentTime.setSeconds($scope.currentTime.getSeconds() + 60);
function _(x) {
console.log(angular.element(document.getElementById(x)));
return angular.element(document.getElementById(x))[0];
}
$scope.interval = $interval(function() {
if ($scope.sec === 0) {
$scope.min--;
$scope.sec = 60;
}
$scope.sec--;
}, 1000);
$scope.$watch('sec', function() {
if ($scope.min === 0 && $scope.sec === 0) {
$interval.cancel($scope.interval);
window.alert('Time Up!!!');
$scope.pos = $scope.questions.length;
$scope.temp = true;
$scope.renderQuestion();
}
})
$scope.renderQuestion = function() {
if ($scope.pos >= $scope.questions.length) {
$scope.ques = false;
if (!$scope.temp) { $scope.temp = false;
$interval.cancel($scope.interval);
}
$scope.showscore = Math.round($scope.correct / $scope.questions.length * 100);
$scope.minuteleft = parseInt(($scope.totalsecoriginal - $scope.totalsec) / 60, 10);
$scope.pos = 0;
return false;
}
$scope.question = $scope.questions[$scope.pos][0];
$scope.chA = $scope.questions[$scope.pos][1];
$scope.chB = $scope.questions[$scope.pos][2];
$scope.chC = $scope.questions[$scope.pos][3];
}
$scope.checkAnswer = function() {
$scope.choices = angular.element(document.getElementsByName('choices'));
$scope.choice = -1;
for (var i = 0; i < $scope.choices.length; i++) {
if ($scope.choices[i].checked) {
$scope.choice = $scope.choices[i].value;
$scope.choices[i].checked = false;
}
}
if ($scope.choice == $scope.questions[$scope.pos][4]) {
$scope.correct++;
}
$scope.pos++;
$scope.renderQuestion();
};
$scope.renderQuestion();
});
Thanks in advance.

Related

Firebase Call to the dynamic Reference not giving proper output

i am creating a chat application for the browser using angular 1 and ionic 1
here is my controller and view for that
the problem is when the new message comes in the selected room which is current room watch variable and below console giving me proper output but that same method getting called twice giving me proper output at fist call but after that he gives me main node output.
$scope.firstLoad='';
$scope.directLoad='';
$scope.text = "Tap on name to open chat !";
$scope.myUid = localStorage.uid;
$scope.rooms = [];
$scope.roomsfound = 0;
$scope.roomswait = 1;
$scope.name = "";
$scope.number = "";
$scope.currentRoomId="";
$scope.is_select_user = 0;
$scope.loadDetails = function (roomId, contactName, phone, name) {
$timeout(function () {
$scope.firstLoad=false;
},2000);
$rootScope.showLoading("loadchat");
$scope.currentRoomId="";
$scope.name = "";
$scope.number = "";
$scope.name = name;
$scope.number = phone[0] == '1' ? phone.slice(1) : phone;/*to stipe out 1 from the phone number in view*/
$scope.is_select_user = 1;
$scope.roomName = "Chat";
$scope.chats = [];
$scope.chats.length = 0;
$scope.roomId = '';
$scope.roomId = roomId;
$scope.roomName = contactName;
firebase.database().ref('messages/' + $scope.roomId).once('value', function (data) {
$timeout(function () {
var tempArr = [];
data.forEach(function (data) {
tempArr.push({
key: data.key,
content: data.val().message,
createdAt: data.val().timestamp,
from: data.val().sendBy,
to: data.val().sentTo,
direction: data.val().direction,
status: data.val().status,
type: data.val().type
})
});
$scope.chats = tempArr;
});
});
$scope.currentRoomId= $scope.roomId;
console.log("In Load Details "+$scope.currentRoomId);
if($scope.firstLoad == false){
firebase.database().ref('rooms/' + $scope.myUid +'/'+$scope.roomId ).update({
isRead:'true'
})
}
$scope.Scroll_top();
$rootScope.hideLoading("loadchat");
}
/*Live Chat Listner for Current Room*/
$scope.$watch(
"currentRoomId",
function handleMessageChange( newValue, oldValue ) {
$timeout(function () {
firebase.database().ref('messages/'+$scope.currentRoomId+'/').on('value', function (data) {
console.log('messages/'+$scope.currentRoomId);
if($scope.currentRoomId != ""){
var liveChatArr = [];
$scope.chats = [];
data.forEach(function (data) {
liveChatArr.push({
key: data.key,
content: data.val().message,
createdAt: data.val().timestamp,
from: data.val().sendBy,
to: data.val().sentTo,
direction: data.val().direction,
status: data.val().status,
type: data.val().type
})
});
$scope.chats = [];
$scope.chats.length=0;
if( $scope.chats.length == 0)
$scope.chats=liveChatArr ;
else{
$scope.chats = [];
$scope.chats.length=0;
$scope.chats=liveChatArr ;
}
$scope.Scroll_top();
}
});
},3000);
});
/*End Live Chat Listener*/
/*Send New Message*/
$scope.data = {};
$scope.sendMessage = function (roomId, message, name, phone, contactName) {
Chats.send(roomId, $scope.myUid, message);
document.getElementById("mymsg").value = "";
$scope.data.message='';
};
/* End Send New Message*/
/* Live Room Listner*/
firebase.database().ref('rooms/' + $scope.myUid).orderByChild('lastMessageAt').on('value', function (data) {
$scope.liverooms = [];
$scope.liverooms.length = 0;
$scope.rooms = [];
$scope.rooms.length=0;
$timeout(function () {
var unique = function(origArr) {
//console.log(origArr);
var newArr = [];
var origLen = origArr.length;
var found, x, y;
for (x = 0; x < origLen; x++) {
//console.log(x);
found = undefined;
for (y = 0; y < newArr.length; y++) {
if (origArr[x] === newArr[y]) {
found = true;
break;
}
}
if (!found) {
newArr.push(origArr[x]);
}
}
return newArr;
}
data.forEach(function (data) {
var ref=firebase.database().ref('rooms/' + $scope.myUid);
var key = data.ref.key;
var fields = key.split('_');
var len = fields.length;
var mobile = fields[len - 1];
$scope.liverooms.push({
roomId: key,
contactName: data.val().contactName,
contactfName: (data.val().contactName.split(' '))[0],
lastMessage: data.val().lastMessage,
lastMessageAt: data.val().lastMessageAt,
lastMessageDirection: data.val().lastMessageDirection,
phone: mobile[0] == '1' ? mobile.slice(1) : mobile,
isRead:data.val().isRead
});
});
$scope.rooms = [];
$scope.rooms.length=0;
if( $scope.rooms.length == 0 ){
$scope.rooms=unique($scope.liverooms).reverse();
}else{
$scope.rooms = [];
$scope.rooms.length=0;
$scope.rooms=unique($scope.liverooms).reverse();
}
//console.log($scope.rooms);
});
$scope.roomswait = 0;
if ($scope.rooms.length > 0) {
$scope.roomsfound = 1;
}
});
/* End Live Room Listner*/
VIEW
<div class="content-wrapper">
<div class="container-fluid">
<div class="col-lg-3 searchmain-box">
<br>
<div class="input-group col-sm-6 col-xs-3 col-md-12 mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon radius-left search-box"><i class="fa fa-search"></i></div>
<input type="text" class="form-control radius-right search-box" ng-model="search" id="inlineFormInputGroup" placeholder="Search">
</div>
<br>
<div class="col-md-12 text-center" ng-show="roomswait == 1">
<img src="img/loading.gif" width="30">
<br>
<h5 class="text-white">Please Wait.. Loading Chats</h5>
</div>
<ul class="list-group user-list" ng-show="roomsfound == 0">
<li class="list-group-item user-list" style="cursor:pointer;outline:none" ng-if="room" ng-repeat="room in rooms| filter:search " ng-init="($first && firstLoad) ? loadDetails(room.roomId, room.contactName + ' (' + room.phone + ')', room.phone, room.contactName) : ''" type="item-text-wrap" ng-click="loadDetails(room.roomId, room.contactName + ' (' + room.phone + ')', room.phone, room.contactName)">
<!--<li class="list-group-item user-list" ng-repeat="room in rooms| orderBy:'lastMessageAt':true | filter:search" type="item-text-wrap" ng-click="loadDetails(room.roomId, room.contactName + ' (' + room.phone + ')', room.phone, room.contactName)">-->
<div class="user-profile" ng-if="room.contactName == name && room.phone == number">
<span><img src="img/liveicon.png"></span>
</div>
<div class="user-name" >
<h4 class="ma-0" ng-class="{'user-live':room.contactName == name && room.phone == number , 'dark-text':(room.contactName != name || room.phone != number) && room.isRead != 'false' , 'not_read':room.isRead == 'false'}" >
{{room.contactName}}
<span class="live-chaticon"></span>
</h4>
<span style="float:left"><img src="img/phone.png"/></span>
<p class="user-phoneno mb-0" style="padding:5px;margin-left: 16px;" ng-class="{'not_read':room.isRead == 'false'}">
{{room.phone| bcTelephone:'format'}}
</p>
<p class="user-message mb-0" style="font-size: 12px;" ng-show="room.lastMsg != ''" ng-class="{'not_read':room.isRead == 'false', 'dark-text':room.isRead == 'true'}">
<span ng-if="room.lastMessageDirection == 'out'">You:</span>
<span ng-if="room.lastMessageDirection == 'in'">{{room.contactfName}}:</span>
{{(room.lastMessage| limitTo: 20) + (room.lastMessage.length > 20 ? '..' : '')}}
</p>
</div>
<div class="user-time">
<p class="dark-text">
<span class="time2" ng-show="room.lastMessageAt != ''" am-time-ago="room.lastMessageAt"></span>
</p>
</div>
</li>
</ul>
</div>
<div class="recent-bg" block-ui="loadchat" style="width:61%;position:fixed;top:0;right:0;background-color:white">
<div class="recent-order">
<!-- <div class="recent-text ">
<h4 class="user-name">{{name}} <span class="live-chaticon"></span></h4>
<h5> <span style="float:left"><img src="img/phone.png" height="20px"/></span> {{number| bcTelephone:'format'}} </h5>
</div>-->
<div class="recent-text ">
<div class="row">
<div class="col-md-3">
<h4 class="user-name">{{name}} <span class="live-chaticon"></span></h4>
<!--<h5 class="user-number">{{number}} </h5>-->
<!--<h5 class="user-number"> {{number| bcTelephone:'format'}} </h5>-->
<h5> <span style="float:left"><img src="img/phone.png" height="20px"/></span> {{number| bcTelephone:'format'}} </h5>
</div>
</div>
</div>
</div>
<div class="col-12 pa-0">
<h5 ng-if="text != ''" class="text-center">{{text}}</h5>
<div class="table-responsive">
<div class="frame">
<div ng-show="chats.length != 0">
<ul class="message-box">
<li ng-repeat="chat in chats| orderBy:'createdAt':false" ng-if="chat" ng-class="{'pull-right default-user ': chat.direction == 'out','pull-left client-user':chat.direction != 'out'}">
<p>{{chat.content}} <br>
<span style="font-size: 10px;" am-time-ago="chat.createdAt" ng-class="{'pull-right default-user': chat.direction == 'out','pull-left client-user':chat.direction != 'out'}"></span>
<br>
<span style="font-size: 10px; float: right" > {{chat.status}}</span>
</p>
</li>
</ul>
</div>
<div class="message-sendbtn" style="position:fixed;width:61%" ng-show="is_select_user">
<div class="input-group">
<input type="text" class="form-control message-control" id="mymsg" placeholder="Your message" ng-model="data.message" aria-label="Recipient's username" aria-describedby="basic-addon2" ng-enter="sendMessage(roomId, data.message, name, number, roomName)">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This is My View
I am getting issue when new message comes in node Contact list which is Room array getting double records and when i send message some time its not showing live status of message and some time it messes up with wrong node (Current Room)
By using on("value") method is getting called multiple times.
Kindly help me i am stuck here.

Nested ng-repeat causing problems

I have to deal with a situation where there will be a question and its answers will be dynamically generated. The issue is when i add one question and add its answers then when i add another question then it already contains the same answers as above question.
For Example:
Q. Select ice cream flavour
A. Chocolate
B. Vanilla
Now When i Add another question
Q. Select ice cream company
Now, here it shows
A. Chocolate
B. Vanilla
Following is my code :
<div class="col-lg-12">
<div ng-controller="CustomizationCtrlr">
<form name="CustomizationForm" ng-submit="SaveCustomization(CustomizationForm.$valid)" novalidate>
<div>
<div class="inputDiv">
#Html.TextBoxFor(model => model.GroupTitle, new { name = "GroupTitle", ng_model = "QuestionGroup.GroupTitle", #class = "form-control", maxlength = "65", placeholder = "GroupTitle" })
<br />
</div>
<div class="formgroup" ng-repeat="Question in Questions">
<div class="inputDiv form-group" id="" ng-repeat="QuestionItem in QuestionItems" >
#Html.TextBoxFor(model => model.QuestionItemText, new { name = "QuestionItemText", ng_model = "QuestionItem.Text", #class = "form-control", placeholder = "Question Item Text", required = "required" })
<button ng-show="showAddQuestionItem(QuestionItem)" ng-click="AddQuestionItem($parent.$index)">Add question item</button>
<br />
</div>
<button ng-show="showAddQuestion(Question)" ng-click="AddQuestion()">Add question</button>
</div>
</div>
<button type="submit" name="btnPost" class="btn save-btn" onclick="ValidateForm()">Save Customizations</button>
</form>
</div>
</div>
And following is my script:
<script>
var app = angular.module('ProductCatalog.controllers', [])
.controller('CustomizationCtrlr', function ($scope, $http) {
$scope.AddQuestionItem = function (parentIndex) {
var newItemNo = $scope.QuestionItems.length + 1 + "-" + parentIndex;
$scope.QuestionItems.push({ 'id': 'qi' + newItemNo });
}
$scope.showAddQuestionItem = function (QuestionItem) {
return QuestionItem.id === $scope.QuestionItems[$scope.QuestionItems.length - 1].id;
};
$scope.QuestionItems = [{ id: 'qi1', Text: '' }];
$scope.AddQuestion = function () {
var newItemNo = $scope.Questions.length + 1;
$scope.Questions.push({ 'id': 'q' + newItemNo });
}
$scope.showAddQuestion = function (Question) {
return Question.id === $scope.Questions[$scope.Questions.length - 1].id;
};
$scope.Questions = [{ id: 'q1', Text: '' }];
})
</script>
You always iterate over the same reference of QuestionItems on your scope.
If you want to connect the answers to the question you need to somehow create unique answer arrays per question
One way to do it is save the answers in the question instance in a property and then ng-repeat that
<div class="formgroup" ng-repeat="Question in Questions">
<div class="inputDiv form-group" id="" ng-repeat="QuestionItem in Question.QuestionItems" >
#Html.TextBoxFor(model => model.QuestionItemText, new { name = "QuestionItemText", ng_model = "QuestionItem.Text", #class = "form-control", placeholder = "Question Item Text", required = "required" })
<button ng-show="showAddQuestionItem(QuestionItem)" ng-click="AddQuestionItem($parent.$index, Question)">Add question item</button>
<br />
</div>
And in the JS:
$scope.Questions = [{ id: 'q1', Text: '', QuestionItems: [{ id: 'qi1', Text: '' }] }];
$scope.AddQuestionItem = function (parentIndex, parentQuestion) {
var newItemNo = $scope.QuestionItems.length + 1 + "-" + parentIndex;
parentQuestion.QuestionItems.push({ 'id': 'qi' + newItemNo });
}
The approach you have contains different scope for Questions and QuestionItems. Whenever, you add a new Question, the Question Items is already populated with previous entries from the previous input.
There is a need to change the data structure here, keep an array of questions and a property within an array for the Question Items.
$scope.Questions = [{
"Id": "q1",
"QuestionItems": [{
"Id": "qi1",
"Text": ""
}]
}]
This way you can have Question and its items grouped together.
See the snippet below, I had to remove the .net controls for the demo purpose, you can replace the input with the razor controls you had earlier.
var app = angular.module("MyApp", []);
app.controller('CustomizationCtrlr', function($scope, $http) {
$scope.Questions = [{
"Id": "q1",
"QuestionItems": [{
"Id": "qi1",
"Text": ""
}]
}]
$scope.AddQuestionItem = function(ques) {
var newItemNo = ques.QuestionItems.length + 1
ques.QuestionItems.push({
'Id': 'qi' + newItemNo,
"Text": ""
});
}
$scope.showAddQuestionItem = function(QuestionItem) {
return QuestionItem.id === $scope.QuestionItems[$scope.QuestionItems.length - 1].id;
};
$scope.AddQuestion = function() {
var newItemNo = $scope.Questions.length + 1;
$scope.Questions.push({
"Id": "q" + newItemNo,
"QuestionItems": [{
"Id": "qi1",
"Text": ""
}]
});
}
$scope.showAddQuestion = function(Question) {
return Question.id === $scope.Questions[$scope.Questions.length - 1].id;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="MyApp">
<div class="col-lg-12">
<div ng-controller="CustomizationCtrlr">
<form name="CustomizationForm" ng-submit="SaveCustomization(CustomizationForm.$valid)" novalidate>
<div>
<div class="inputDiv">
<input type="text" ng-model="QuestionGroup.GroupTitle" placeholder="GroupTitle" />
<br />
</div>
<div class="formgroup" ng-repeat="Question in Questions">
<div class="inputDiv form-group" id="" ng-repeat="QuestionItem in Question.QuestionItems">
<input type="text" ng-model="QuestionItem.Text" placeholder="Question Item Text" />
<button ng-click="AddQuestionItem(Question)">Add question item</button>
<br />
</div>
<button ng-click="AddQuestion()">Add question</button>
</div>
</div>
<button type="submit" name="btnPost" class="btn save-btn" onclick="ValidateForm()">Save Customizations</button>
</form>
<pre>{{Questions | json}}</pre>
</div>
</div>
</body>

Nested ng-repeat and radio or checkbox inputs not working

I am trying to show list of questions and their choices by nested ng-repeat, I have seen plenty of similar questions but still could not fix my issue. My issue here is I could see the list of questions but the choices are not getting displayed and in the developer tools I could only see the commented ng-repeat line in place of choices.
Here is my View
<div ng-repeat ="question in questions track by $index" class="panel panel-default" ng-show="showQuestions">
<div class="panel-heading">
<div class="panel-title">
<a href="div#{{$index}}" class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" >
{{question.QuestionTxt}}
</a>
<div class="row height"></div>
<div class="row" ng-show="question.QuestionTypeTxt == 'RadioButton'">
<div class="col-xs-3" ng-repeat ="answer in questions.QuestionAnswers track by $index">
<input type="radio" ng-model="selectedChoice.choice" ng-value="{{answer.AnswerTxt}}" name="{{question.QuestionTxt}}"/>{{answer.AnswerTxt}}
</div>
</div>
<div class="row" ng-show="question.QuestionTypeTxt == 'Checkbox'">
<div class="col-xs-3" ng-repeat ="answer in questions.QuestionAnswers track by $index">
<input type="checkbox" ng-model="selectedChoice.choice" ng-value="{{answer.AnswerTxt}}" name="{{question.QuestionTxt}}"/>{{answer.AnswerTxt}}
</div>
</div>
</div>
</div>
</div>
Here is my Controller
$scope.questions = [];
$scope.selectedChoice = { choice:"" };
$scope.addQuestions = function () {
$scope.showQuestions = true;
rmat3Service.getQuestionsForSection().then(function (data) {
angular.forEach(data,function(a) {
$scope.questions.push(a);
});
});
}
This is my Json data:
var questions = new List<Question>();
var answers = new List<QuestionAnswer>();
answers.Add(new QuestionAnswer()
{
AnswerTxt = "Yes",
});
answers.Add(new QuestionAnswer()
{
AnswerTxt = "No"
});
answers.Add(new QuestionAnswer()
{
AnswerTxt = "Yes Verified"
});
answers.Add(new QuestionAnswer()
{
AnswerTxt = "Not Applicable"
});
questions.Add(new Question()
{
QuestionId = 1,
QuestionTxt = "Are aisles clear of product on the floor?",
QuestionTypeTxt = "RadioButton",
QuestionAnswers = answers
});
questions.Add(new Question()
{
QuestionId = 2,
QuestionTxt = "Automated Car Wash",
QuestionTypeTxt = "Checkbox",
QuestionAnswers = answers
});
return Json(questions, JsonRequestBehavior.AllowGet);
The issue is that you're attempting to loop questions.QuestionAnswers which doesn't exist. It should be question.QuestionAnswers:
<div class="col-xs-3" ng-repeat ="answer in question.QuestionAnswers track by $index">

Angularjs ng-repeat sum the fields

Hi I am new to angularjs I have a problem in calculation the sum of the field my code is like this
<div ng-repeat="(key,item) in expenses_data | groupBy: 'category_name'">
<h4 ng-cloak><i class="fa fa-plus-circle"></i> {{ key }}</h4>
<div class="form-group" ng-repeat="expn_head in item">
<label class="col-sm-3 control-label">{{ expn_head.name }}</label>
<div class="col-sm-2">
<input type="text" class="form-control input-sm" ng-model="expenses.expenditure_head[expn_head.id]">
</div>
</div>
</div>
How do I sum up all the expenses.expenditure_head value entered and put it in the new text field. Is there any function like this:
<input type=text ng-value="{{ sum() }}">
and js
$scope.sum = function() {
var total = 0;
for (var i = 0; i < $scope.expenses.expenditure_head; i++) {
var myValue = $expenses.expenditure_head[i];
total += myValue;
}
return total;
}
json
[
{
"id":23,
"name":"Agency Commission",
"expenditure_category_id":1,
"category_name":"Main"
},
{
"id":22,
"name":"Bonus to Local Staff",
"expenditure_category_id":1,
"category_name":"Main"
},
{
"id":48,
"name":"Advance for Expenses",
"expenditure_category_id":2,
"category_name":"Other Dept's Budget Exp"
},
{
"id":49,
"name":"Agency TDS",
"expenditure_category_id":2,
"category_name":"Other Dept's Budget Exp"
}
]
Can anyone show me the right direction? I have trying this for a day.
The right way is to do so inside the controller. Create a function call it getSum()
$scope.getSum = function(){
var total = 0;
for(var i = 0; i < $scope.someVar; i++){
var myValue = $someVar[i];
sum += myValue;
}
return sum;
};
Then inside your code you do something like
<td>Total: {{ getSum() }}</td>

Angularjs why $scope.products not update data in controller

I have problem, would you help me. I have 2 views below. In the first, i use table, $scope.products can update data when change value input product.pick_qty. But in the seconds view, i use list, $scope.products can not update.
The first view html
<div class="row" ng-repeat="product in products">
<div class="col col-40">
<span>{{`product.product_name`}}</span></br>
<span class="italic">Size: {{product.size}}, </span>
<span class="italic">Color: {{product.color}}</span>
</div>
<div class="col col-20">{{`product.barcode`}}</div>
<div class="col col-20">{{product.request_qty}}</div>
<div class="col col-20"><input type="text" class="col-50 pick_qty" ng-model="product.pick_qty" /></div>
</div>
The seconds view html
<div class="list animate-fade-slide-in-right" ng-repeat="product in products ">
<a class="item item-icon-right in">
<h2>{{product.product_name}}</h2>
<p>
<span class="italic">Size: {{product.size}}, </span>
<span class="italic">Color: {{product.color}}, </span>
<span class="italic">Request Qty: {{product.request_qty}}</span>
</p>
<label class="item-input item-floating-label">
<span class="input-label">Pick Qty</span>
<input type="text" placeholder="Pick Qty" ng-model="product.pick_qty" >
pick_qty: {{product.pick_qty}}
products :{{products}}
</label>
</a>
</div>
Here is the same my controller ($scope.products i get from server have same structure), i want to $scope.products update field pick_qty when i change value input.
$scope.products = [
{
barcode: null,
color: "Black",
product_id: "528",
product_name: "TriBeCa Skinny Jean",
request_qty: 10,
size: "27"
},
{
barcode: null,
color: "Black",
product_id: "370",
product_name: "Isla Crossbod",
request_qty: 10,
size: "27"
}
];
var addParamsConfirm = function(){
var paramsConfirm = {};
paramsConfirm.data = [];
angular.forEach($scope.products, function(product){
angular.forEach(listPicked, function(item){
if(product.product_id === item.product_id){
if( product.pick_qty <= ( product.request_qty - item.picked_qty )){
paramsConfirm.data.push({
product_id: product.product_id,
qty: product.pick_qty
});
paramsConfirm.action = action.pick;
paramsConfirm.shop_id = 'BBB';
}
}
else {
if( (product.pick_qty > 0) && (product.pick_qty <= product.request_qty)){
paramsConfirm.data.push({
product_id: product.product_id,
qty: product.pick_qty
});
paramsConfirm.action = action.pick;
paramsConfirm.shop_id = 'BBB';
}
}
})
});
return paramsConfirm;
}

Resources