How to add dynamic fields with angularjs - angularjs

I am working on a QA app where i need to add multiple answers to a question as per requirement dynamically. for this in my form I have a question field , an answer field and a Boolean correct field to tell if the answer choice is correct or not. I have given a button add another answer which create a new answer field when clicked.I want to give ng-model name dynamically so that I can easily retrieve the value of ng-model.
For this I have created a controller which is like
app.controller('questionsCtrl', function ($scope) {
$scope.question={};
$scope.question.answers=[];
$scope.answer_choices=[];
var choice=1;
$scope.addAnswerField=function(){
$scope.answer_choices.push(choice);
choice++;
}
$scope.addAnswerChoice=function(){
$scope.question.answers.push({});
}
});
My HTML code is:
<div class="container">
<form ng-submit="createQuestion()">
<textarea class="form-control" ng-model='question.question_text'></textarea>
<textarea class="form-control" ng-model="question.answer_choice_1"></textarea>
<label class="checkbox-inline">
<input type="radio" name="correct" ng-model="question.correct_1" />
Correct
</label>
<div ng-repeat="choice in answer_choices">
<textarea class="form-control" ng-model="question.answers.$index[answer]">
</textarea>
<label class="checkbox-inline">
<input type="radio" name="correct" ng-model = "question.answers.$index[correct]" />
</label>
</div>
<button class='btn btn-primary' type="submit">Submit</button>
</form>
<button class="btn btn-default" ng-click="addAnswerChoice()">Add Answer</button>
</div>
I want to do something like when i add a new answer choice a new empty object is pushed in the question.answers array and this objects first key answer hold the value of question field and second key ` like
question.answers=[
{'answer':'',correct:''},
{'answer':'',correct:''},
{'answer':'',correct:''},
{'answer':'',correct:''},
]
Suggest me how can i do this . There is only one error that using $index i am unable to assign value to the array object at the same index in question.answers array.
Or if there is any other better way suggest me.
Help will be appreciated.

You are making just a small mistake. Correct your syntaxes and it will work fine
replace your ng-repeat div with this code
<div ng-repeat="choice in choices">
<label class="checkbox-inline"> Choice</label>
<textarea class="form-control" ng-model="question.answers[$index].answer">
</textarea>
<label class="checkbox-inline">
<input type="radio" name="correct" ng-model="question.answers[$index].correct_answer" value="1" />
Correct
</label>
</div>
And assign values to the radio buttons or these will not show in your object.

Related

Input text is empty using ng-model if value is provided

I passed an array value in my view with $userdata.
In my view, there's a button there that will show a modal when triggered. This modal will show the user data using the $userdata variable.
Now, I used angular js for my form inputs.
For example:
div class="form-group">
<label for="company_name" class="col-sm-12 control-label">Company Name</label>
<div id="company_name" class="col-sm-12">
<input type="text" class="form-control" name="company_name" value="{{$userData['company']['name']}}" ng-model="user.company_name" ng-required="true">
</div>
<div class="col-sm-12">
<span ng-show="userForm.company_name.$error.required && userForm.company_name.$touched"><br> <small><i>Name field is required</i></small></span>
</div>
</div>
The problem here is the input is not showing any value.
Why so? But when I removed the ng-model and just used a plain input field, the value will be shown.
You have to remove value="..." from input, ng-model will control it. look at this example.
<input type="text" class="form-control" name="company_name" ng-model="user.company_name" ng-required="true">

How to obtain values from input fields with Angular JS after ng-repeat

I'm new in AngulsrJS and I've got following code:
<form ng-if="editorCtrl.edit" class="form-horizontal" role="form" ng-submit="editorCtrl.saveEntry()">
<div class="form-group">
<div class="col-md-6" ng-repeat="(key,field) in editorCtrl.editEntry">
<label>{{key}}</label>
<input type="text" class="form-control" value={{field}} />
</div>
</div>
<!-- ng-model="editorCtrl.toSave[key]" ng-value="{{field}}" that part was in input attributes -->
<div class="form-group">
<div style="padding-left:110px">
<input type="submit" value="Update selected entry" ng-disabled="form.$invalid" class="btn btn-primary"/>
</div>
</div>
</form>
Now I need to obtain values from input fields. I tried to use ng-model="editorCtrl.toSave[key], but it's not working in a correct way.
Any suggestions how to resolve this situation ?
if you can consider no necesary the "toSave" object maybe you can use the 2-way data binding properly only using editEntry Object :
<input type="text" class="form-control" value={{field}} ng-model="editorCtrl.editEntry[key]"/>
In this way after a submit you will get editEntry with the fields modifieds (or not), here is an example
https://jsfiddle.net/pv8qrwty/1/
run the example and if you modified the fields after you press the submit button it will be displayed in your browser console
hope this help ! and sorry for my english !

getting value from angular radio buttons

I am trying to follow the angular docs for radio buttons.
https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
Don't know what I'm doing wrong.
Ultimately, I want the div "stuff" to have class "muted" if radio option 3 is selected.
my html:
<form name="shippingVm.MasterCartonForm" ng-controller="shippingControler as shippingVm" >
[{{shippingVm.shipOption.val}}]
<div class="col-sm-3 col-sm-offset-1">
<label class="radio-inline">
<input type="radio" ng-model="shippingVm.shipOption.val" name="shippingOptions" ng-value="one" />
I will call Purolator for a pickup.
</label>
</div>
<div class="col-sm-3">
<label class="radio-inline">
<input type="radio" ng-model="shippingVm.shipOption.val" name="shipOptions" ng-value="two" />
I will deliver them to Purolator.
</label>
</div>
<div class="col-sm-4">
<label class="radio-inline">
<input type="radio" ng-model="shippingVm.shipOption.val" name="shipOptions" ng-value="muted" />
I will deliver them to the Wizmo warehouse myself.
</label>
</div>
<div class="ng-class="shippingVm.shipOption.val">
stuff
</div>
</form>
my controller:
vm.shipOption = {val: "NOT-muted"};
This debugging line in the HTML checks to see if I'm getting the right value:
[{{shippingVm.shipOption.val}}]
It starts with [NOT-muted] - as it should. But the moment I select any radio button it goes blank.
According to the docs, clicking a radio should pass the radio's value into the model.
What am I missing?
Your ng-class is incorrect. See the below snippet for an example of what it should be. The second problem is that you want value instead of ng-value. From: https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
value The value to which the ngModel expression should be set when selected. Note that value only supports string values, i.e. the scope model needs to be a string, too. Use ngValue if you need complex models (number, object, ...).
ngValue Angular expression to which ngModel will be be set when the radio is selected. Should be used instead of the value attribute if you need a non-string ngModel (boolean, array, ...).
.muted {
color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<label>Chicken or the Egg?</label>
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="chickenEgg" value="chicken" ng-model="formData.chickenEgg">Chicken
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="chickenEgg" value="egg" ng-model="formData.chickenEgg">Egg
</label>
</div>
</div>
<div ng-class="{'muted': formData.chickenEgg === 'egg'}">
stuff
</div>
</div>
Oh, I see it now.
The radio buttons should have value="muted" not ng-value="muted".
ng-value is only used in a special case.

Angular.js required and ng-required not working for <textarea></textarea>

I can not get Angular.js required or ng-required to work. I want it to where if the user hits ok, they have to have some text in the textbox.
<div class="modal-body">
<p>Your change will be logged. Please provide a ticket number or comment for reference</p>
<div class="row">
<div class="span4">
<textarea type="text" class="form-control"
ng-model="commentBox.text"
ng-required="commentBox.text">
</textarea>
</div>
</div>
</div>
Scratching my head.....
two things:
make sure that value you are passing to ng-required is boolean (to be technically correct, it should evaluate to boolean)
<textarea type="text" class="form-control"
ng-model="commentBox.text"
ng-required="commentBox.textRequired">
</textarea>
//somewhere in your controller
$scope.commentBox.textRequired = true
you would need form.$invalid on your button
<button type="submit" ng-disabled="formname.$invalid" ng-click="onsubmit()"></button>
so to complete it
<ng-form name="exampleForm">
<textarea type="text" ng-model="commentBox.text" ng-required="true"></textarea>
<button ng-disabled="exampleForm.$invalid" ng-click="onsubmit()"></button>
</ng-form>
also without adding another prop, you could set it to
ng-required="!!commentBox.text"

Issue with ng-model and ng-repeat, duplicate forms

I have a page where multiple forms are created based on ng-repeat. Everything works fine until write something into the input and everything gets duplicated on all the other repeated forms input elements. I have used ng-model="Notify.message" which is nothing but object which takes the value from the input and sends to control on button submit and hence rest of the logic.
I am looking for when if one form is been filled, other forms should keep quite and shouldn't duplicate the values written in input text of form 1.
Here is the code:
<div data-ng-show="alluserposts.length > 0">
<div id="b{{userpost.id}}" data-ng-repeat="userpost in alluserposts" >
<div class="row" style="margin-left: -5px">
<form class="text-center" role="form" id=f1{{userpost.id}} name="userForm"
ng-submit="notify(userForm.$valid, userpost, apiMe)" novalidate>
<div class="row">
<div class="col-xs-8 col-md-4">
<div class="form-group">
<input data-container="body" data-toggle="popover" data-placement="top"
data-content="Any message which you would like to convey to post owner"
type="text" ng-model="Notify.message" data-ng-init="Notify.message=''"
id="u{{userpost.id}}"
placeholder="Enter a Message or Phone number" class="form-control"
required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">It is
required.</p>
<script>$(function () {
$("[data-toggle='popover']").popover();
});
</script>
<input type="hidden" ng-model="Notify.loggedInEmail"
ng-init="Notify.loggedInEmail = result.email"/>
<input type="hidden" ng-model="Notify.postId" ng-init="Notify.postId = userpost.id"/>
<input type="hidden" ng-model="Notify.destEmail"
ng-init="Notify.destEmail = userpost.userEmail"/>
</div>
</div>
<div ng-show="loginStatus.status == 'connected'" class="col-xs-4 col-md-2">
<button class="btn btn-primary" ng-disabled="userForm.$invalid || !userForm.$dirty"
type="submit">
Notify Post Owner
</button>
</div>
</div>
</form>
</p>
</div>
</div>
</div>
</div>
Issue fiddle - jsfiddle
Here you can when something is written in one input, other gets filled too :( . Also Notify is a Java mapped object and message is a variable inside it. Pls let me know how can this can be segragated!
You bind all of your inputs to same variable on $scope.
You must bind every text box to a distinct variable on $scope:
View:
<ul ng-repeat="post in posts">
<li>{{$index}}
<input type="text" ng-model="emails[$index]"/>
</li>
</ul>
Controller:
$scope.emails = [];
I am also at the starting phase of angularjs.
I have faced the same issue few days ago and resolved it by providing dynamic model name in ng-model like
<input type="text" ng-model="Notify[post.userEmail]" ng-init="Notify[post.userEmail] = post.userEmail" />
Working fiddle: Fiddle

Resources