Nested ng-repeat causing problems - angularjs

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>

Related

angular radio button set checked

i have multiple radio button groups
i need to set one of each group (maybe none) as selected
datasource
html Code
<div class='row' ng-show="mk.selectedTypeAttributesID.length != 0">
<div class='col-xs-6 col-sm-6 col-md-6 col-lg-6' ng-repeat="att in selectedTypeAttributesID">
<div class="switch-field">
<div class="switch-title">{{att.name}}</div>
<div>
<input ng-repeat-start="val in att.Values" class="bttn-input" type="radio" id="switch_{{val.val}}" name="switch_{{att.id}}" value="{{val.val}}" ng-click="mk.AttChange(att.id,val.val)" />
<label ng-repeat-end class="bttn-input" for="switch_{{val.val}}">{{val.val}}</label>
</div>
</div>
</div>
</div>
i need to use the value of 'Selected' On the datasource to set the checkbox
source Update
You need to use ng-model to select the radio button..
Where ng-model holds the selected value as shown below.
$scope.options = [{Selected: false, val: "red"}, {Selected: true, val:"Black"}, {Selected: false, val:"Pink"}];
$scope.selected = undefined;
var findResult = $scope.options.find(function(x){ return x.Selected == true });
if(findResult){
$scope.selected = findResult.val;
}
Here's a JSFiddle
Edit: Since the sources of the checkboxes are dynamic then build a dynamic selection tree for modal to bind to..
Here's an example:
$scope.options = [{ 0 : [{Selected: false, val: "red"}, {Selected: true, val:"Black"}, {Selected: false, val:"Pink"}]}, { 1 : [{ Selected: false, val: "2" }, { Selected: true, val: "1" }]}];
$scope.choices = [];
for(var i = 0; i < Object.keys($scope.options).length; i++){
var keys = Object.keys($scope.options);
$scope.choices.push({ Id: keys[i], Value: $scope.options[i][keys[i]].find(function(x){ return x.Selected == true }).val });
}
JSFiddle
Are you looking for a solution like so?
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.selectedTypeAttributesID = [{
id: 1,
Values: [{
val: "red",
selected: ""
}, {
val: "green",
selected: ""
}, {
val: "blue",
selected: ""
}]
},
{
id: 2,
Values: [{
val: "1",
selected: ""
}, {
val: "2",
selected: ""
}, {
val: "3",
selected: ""
}]
}
];
$scope.setVal = function(att, index, val) {
for (var k of att.Values) {
k.selected = "";
}
att.Values[index].selected = val;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
<div class='row'>
<div class='col-xs-6 col-sm-6 col-md-6 col-lg-6' ng-repeat="att in selectedTypeAttributesID">
<div class="switch-field">
<div class="switch-title">{{att.name}}</div>
<div>
<input ng-repeat-start="val in att.Values" class="bttn-input" type="radio" id="switch_{{val.val}}" name="switch_{{att.id}}" ng-value="val.val" ng-click="setVal(att, $index, val.val)" />
<label ng-repeat-end class="bttn-input" for="switch_{{val.val}}">{{val.val}}</label>
</div>
</div>
</div>
</div>
<pre>{{selectedTypeAttributesID | json}}</pre>
</div>

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

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.

ng-model into ng-repeat Angularjs

I'm asking if is possible to do something as that in angular
<div ng-app="app">
<div ng-controller="mainController">
<ul ng-repeat="movie in movies |searchFilter:Filter.genre | searchFilter:Filter.name |searchFilter:Filter.pic ">
<li>{{movie.name}}</li>
</ul>
<h2>genre</h2>
<div>
<label>Comedy </label><input type="checkbox" ng-model="Filter.genre.Comedy" ng-true-value="Comedy" data-ng-false-value=''/><br/>
</div>
<h2>PIC</h2>
<label>aa</label><input type="checkbox" ng-model="Filter.pic.aa" ng-true-value="ciao" data-ng-false-value=''/><br/>
<h2>Name</h2>
<label>Shrek</label><input type="checkbox" ng-model="Filter.name.Shrek" ng-true-value="The God" data-ng-false-value=''/><br/>
</div>
</div>
i'm creating a checkbox for filter on different fields (size,name,genre)
ill have a list of avaible sizes,names and genres .
The issue is on ng-model and i tried to write it as "Filter.genre.genre.name" or
"Filter["genre"+genre.name]" and also "Filter.genre[genre.name]" but still not work .
the js.file is
var app =angular.module('app', []);
app.controller('mainController', function($scope) {
$scope.movies = [{name:'Shrek', genre:'Comedy',pic:"cc"},
{name:'Die Hard', genre:'Comedy',pic:"aa"},
{name:'The Godfather', genre:'Drama',pic:"ciao"},
{name:'The Godher', genre:'Comedy',pic:"lel"}];
$scope.genres = [{name:"Comedy"},{name:"Action"},{name:"Drama"}];
});
app.filter('searchFilter',function($filter) {
return function(items,searchfilter) {
var isSearchFilterEmpty = true;
//searchfilter darf nicht leer sein
angular.forEach(searchfilter, function(searchstring) {
if(searchstring !=null && searchstring !=""){
isSearchFilterEmpty= false;
}
});
if(!isSearchFilterEmpty){
var result = [];
angular.forEach(items, function(item) {
var isFound = false;
angular.forEach(item, function(term,key) {
if(term != null && !isFound){
term = term.toLowerCase();
angular.forEach(searchfilter, function(searchstring) {
searchstring = searchstring.toLowerCase();
if(searchstring !="" && term.indexOf(searchstring) !=-1 && !isFound){
result.push(item);
isFound = true;
// console.log(key,term);
}
});
}
});
});
return result;
}else{
return items;
}
}
});
if i make 3 different labels for the field Comedy, Action and Drama with ng-models called as
ng-model="Filter.genre.Comedy" ; ng-model="Filter.genre.Action" and ng-model="Filter.genre.Drama"
it work but it doesnt work if i try to write it into ng-repeat . I hope to have been clearer
In this sample i try to handle your question by change the Model of your page.
we have:
list of movies array => $scope.movies = []
dynamic filters array => $scope.genres = [], $scope.years = [] or more
our target:
Create a dynamic filters to search in movies
what we do
$scope.filterHandler = function (key, value) {}
Run when user start searching on input or select, this function help us to create a filter as object by sending key and value which result is {key:value}
$scope.searchTypeHandler = function (type, dependTo) {}
Run when our filters has some array for example genre has genres as dropdown select, this function help us to return the array which depend to the filter.
var app = angular.module("app", []);
app.controller("ctrl", [
"$scope",
function($scope) {
//your options
$scope.movies = [{
name: 'Shrek',
genre: 'Comedy',
year: 2000
},
{
name: 'Die Hard',
genre: 'Action',
year: 2000
},
{
name: 'The Godfather',
genre: 'Drama',
year: 2015
},
{
name: 'The Godher',
genre: 'Comedy',
year: 2017
}
];
$scope.genres = [{
name: "Comedy"
},
{
name: "Action"
},
{
name: "Drama"
}
];
$scope.years = [{
name: 2000
},
{
name: 2015
},
{
name: 2017
}
];
//
$scope.filter = {}
$scope.filterHandler = function(key, value) {
var object = {};
object[key] = value;
$scope.filter["find"] = object;
};
$scope.searchTypeHandler = function(type, dependTo) {
$scope.filter = {};
$scope.filter.searchType = type;
$scope.filter.options = undefined;
if (dependTo != null) {
$scope.filter.options = $scope[dependTo];
}
};
//default
$scope.searchTypeHandler("name");
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="container" ng-app="app" ng-controller="ctrl">
<div class="page-header">
<div class="row">
<div class="col-lg-12">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<h4>Movies</h4>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 pull-right">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
By {{filter.searchType}}
<span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-menu-left">
<li><a ng-click="searchTypeHandler('genre', 'genres')">Filter By Genre</a></li>
<li><a ng-click="searchTypeHandler('name', null)">Filter By Name</a></li>
<li><a ng-click="searchTypeHandler('year', 'years')">Filter By Year</a></li>
</ul>
</div>
<input ng-hide="filter.options" type="text" class="form-control" ng-model="filter.query" ng-change="filterHandler(filter.searchType, filter.query)">
<select ng-show="filter.options" class="form-control" ng-model="filter.option" ng-change="filterHandler(filter.searchType, filter.option)" ng-options="option.name as option.name for option in filter.options"></select>
</div>
<!-- /input-group -->
</div>
</div>
</div>
</div>
<ul class="list-group">
<li class="list-group-item" ng-repeat="movie in movies | filter: filter.find">
{{movie.name}} - <label class="label label-info">Ggenre: {{movie.genre}}</label> - <label class="label label-default">Year: {{movie.year}}</label>
</li>
</ul>
</div>

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;
}

binding data in ng-repeat angularjs

*This is my html file where i want to repeat chapters which is a array that looks like
My code gives binds the selected checked boxes only (Index values) to true. But i need the entire list of chapters and their i.d's to be retrieved on submit.
Cannot figure out how to iterate it on nested loops *
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-repeat="chapter in chapters">
<label><input type="checkbox" name="checkbox" value="{{chapter}} ng-model="escConfigForm.chapters[$index]" >{{chapter.name}}</label><br>
</span>
<input type="submit" id="save" value="Save" />
$scope.chapters = chapterService.getChapters($scope.isbn);
$scope.submit = function(escConfigForm) {
var postData = {
content_items: JSON.stringify({
"#context" : [],
"#graph" : [ {
"#type" : "ContentItemPlacement",
"placementOf" : {
"#type" : "LtiLink",
"text" : escConfigForm.examName,
"mediaType" : "application/vnd.ims.lti.v1.launch+json",
"title" : "Exam Study Center",
"custom" : {
"dueDate" : escConfigForm.examDueDate,
"targetScore" : escConfigForm.examTargetScore,
"chapters" : escConfigForm.chapters
},
"activityType" : "other",
"activityRefId" : $scope.escId
}
} ]
}),
data: $scope.data
};
postForm($scope.postUrl, postData);
var configData = {
"activityRefId" : $scope.escId,
"dueDate" : escConfigForm.examDueDate,
"targetScore" : escConfigForm.examTargetScore,
"chapters" : escConfigForm.chapters
};
console.log($scope.chapters);
JSON file:
[{"name":"Chapter 1: Negative Messages","id":"832115"},{"name":"Chapter 2: Physics","id":"832115"},...]
I would recommend maintaining a list of the selected objects in the controller.
using this post as referenece: How do I bind to list of checkbox values with AngularJS?
I created this fiddle: http://jsfiddle.net/ruwk5r0v/7/
<div ng-app="formExample">
<div ng-controller="ExampleController"> <span ng-repeat="chapter in chapters" ng-click="checkboxChange($index)" ng-checked="selection.indexOf($scope.chapters[$index]) > -1">
<input type="checkbox" name="checkbox" value="{{$index}}" />
{{chapter.name}}
<br>
</span>
<br>
<input type="submit" ng-click="submitForm()" id="save" value="Save" />
<div> <span ng-repeat="chapter in selection">
<span>
{{chapter.name}}
</span>
<br>
</div>
and the js:
angular.module('formExample', []).controller('ExampleController', ['$scope', function ($scope) {
$scope.chapters = [{
"name": "Chapter 1: Negative Messages",
"id": "832115"
}, {
"name": "Chapter 2: Physics",
"id": "832115"
}];
$scope.submitForm = function () {
console.log(selection);
}
$scope.selection = []
$scope.checkboxChange = function(index){
var chapter = $scope.chapters[index];
var idx = $scope.selection.indexOf(chapter);
if (idx > -1){
$scope.selection.splice(idx, 1);
} else {
$scope.selection.push(chapter);
}
}
}]);
here you can very easily implement your submit function, just use the new selection object.
This really should be moved into a directive, but don't have time to write that right now :P
Here I created a controller for the snippet, and added some data to $scope.chapters object, and it is displaying correctly. The values disappear when selected, but that is another issue.
angular.module('myApp', [])
.controller('myCtrl', ['$scope',
function($scope) {
$scope.chapters = [{
name: 'Chapter 1: Negative Messages',
id: "1",
isSelected: false
}, {
name: 'Chapter 2: Physics',
id: "2",
isSelected: false
}];
$scope.submitItems = function(chapters) {
alert(JSON.stringify(chapters));
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<span ng-repeat="chapter in chapters">
<input type="checkbox" name="checkbox" value="{{chapter}}"
ng-model="chapter.isSelected" />
{{chapter.name}}
</span>
<br>
<form ng-submit="submitItems(chapters)">
<input ng-model="chapters" type="submit" id="save" value="Save" />
</form>
</div>
</div>
Edit: Updated the code to reflect the OP needs.

Resources