add and remove text field dynmaically in angularjs - angularjs

I want to add and remove text fields in angularjs with an add button click. And in the right side of the text fields, which were added there should be a remove option. While I click on the remove the text field should delete.

I would solve this using ng-repeat. Have a look at this example:
Edit updated the code:
angular.module("module",[])
.controller("ctrl",function($scope){
$scope.inputList = [];
$scope.add = function(){
$scope.inputList.push({content:""});
};
$scope.remove = function(input){
var idx = $scope.inputList.indexOf(input);
$scope.inputList.splice(idx,1)
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="module" ng-controller="ctrl">
<div ng-repeat="input in inputList">
<input type="text" ng-model="input.content">
<input type="button" ng-click="remove(input)" value="remove">
</div>
<input type="button" ng-click="add()" value="add">
</div>

You can use ng-repeat to achieve this functionality.
You'll have to add an object in a $scope object's array everytime the user presses Add button and removing the object when the user presses - button.
Here's the code sample.
<span ng-click="addTextBox()"> + </span>
<div ng-repeat="textBox in textBoxes">
<input type='text' />
<span ng-click="removeTextBox(textBox.id)"> - </span>
</div>
The controller goes like this
$scope.textBoxes = [];
$scope.addTextBox = function() {
$scope.textBoxes.push({id: $scope.textBoxes.length +1});
}
$scope.removeTextBox = function(id){
var indexToRemove;
for(i = 0; i < $scope.textBoxes.length; i++){
if($scope.textBoxes[i].id === id){
indexToRemove = i;
}
$scope.textBoxes.splice(indexToRemove, 1);
}
}

You can use this simple way:
HTML
<span ng-repeat="hobby in hobbies track by $index">
<div class="form-group">
<input type='text' ng-model='hobbies[$index]' class="form-control pull-right"/>
<button ng-click = "addHobby()" ng-show="$last">+</button>
<button ng-click = "removeHobby($index)" ng-show="hobbies.length > 1">-</button>
</div>
</span>
Angular Controller
$scope.hobbies = [''];
$scope.addHobby = function() {
$scope.hobbies.push('');
}
$scope.removeHobby = function(index) {
if(index >= 0){
$scope.hobbies.splice(index, 1);
}
}

Related

Get the value of dynamic check boxes in angular js when submitting the form

In my HTML form there are 5 check boxes. How can I check which check boxes are checked or not at the time of the form submission?
I am using this little piece of code. Feel free to take it.
In your controller:
$scope.sentinel = [];
$scope.toggleSelection = function(value) {
// Bit trick, equivalent to "contains"
if (~$scope.sentinel.indexOf(value)) {
var idx = $scope.sentinel.indexOf(value);
$scope.sentinel.splice(idx, 1);
return;
}
$scope.sentinel.push(value);
};
Then in your HTML:
<span ng-repeat="key in $scope.yourarray">
<md-checkbox style="margin-left:30px;" aria-label="Select item"
ng-click="toggleSelection(key)"><span>{{ key }}</span></md-checkbox>
<br/>
</span>
This allows you to have an array of any size and using the sentinel array to register already checked values. If you check again a box, the toogleSelection will prevent you from adding again a value.
You can use the Checklist-model of Angular.js. It is very useful:
var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl1', function($scope) {
$scope.roles = [
'guest',
'user',
'customer',
'admin'
];
$scope.user = {
roles: ['user']
};
$scope.checkAll = function() {
$scope.user.roles = angular.copy($scope.roles);
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push('guest');
};
$scope.showCheckedOnes = function() {
var checkedBoxes = "";
for (var i = 0; i < $scope.user.roles.length; i++) {
checkedBoxes += $scope.user.roles[i] + " ";
}
alert(checkedBoxes);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://vitalets.github.io/checklist-model/checklist-model.js"></script>
<div ng-app="app">
<div ng-controller="Ctrl1">
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}}
</label>
<div>
<div>
<button ng-click="checkAll()" style="margin-right: 10px">Check all</button>
<button ng-click="uncheckAll()" style="margin-right: 10px">Uncheck all</button>
<button ng-click="checkFirst()" style="margin-right: 10px">Check first</button>
<button ng-click="showCheckedOnes()" style="margin-right: 10px">Show checked ones</button>
You can define the array value and map to html.
$scope.checkbox = [];
HTML
<input ng-model="checkbox[0] type="checkbox" />
<input ng-model="checkbox[1] type="checkbox" />
<input ng-model="checkbox[2] type="checkbox" />
<input ng-model="checkbox[4] type="checkbox" />
Or you can define checkbox as object and change checkbox[index] to checkbox[name].

Validation fails for mutually exclusive checkboxes

I have two checkboxes. The validation condition is on form-submit, the form should be valid if and only if one checkbox is checked.
Went about doing like this. Gave the two checkboxes same classname and on ng-click I looped through the checkboxes and found the checked count like this.
$scope.SetCheckDatesCount = function () {
$scope.CheckedDatesCount = 0;
var checkBoxes = document.getElementsByClassName("AcceptedChecks");
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
$scope.CheckedDatesCount++;
}
}
};
Now in markup I set,
ng-required="CheckedDatesCount != 1"
So, that the checkbox will be ng-required when CheckedDatesCount = 0 ||CheckedDatesCount = 2.
But the validation won't work if I check two checkboxes.
Plunkr Demo: https://plnkr.co/edit/ekGCpdXspQAf6zTwDToT?p=preview
I could stop form submit by using an extra check like this. (But is that very clean?)
if (theForm.$invalid && CheckedDatesCount != 1) {
$scope.showMessages = true;
return;
}
Why is the form not invalid when two checkboxes are checked. What am I doing wrong?
you don't have to check the state of the checkobox. i think you could do this-
<div class="row">
<button ng-disabled="!((Interview.InterviewAccepted || Interview.AlternateAccepted) && (Interview.InterviewAccepted != Interview.AlternateAccepted) )" class="btn btn-success" ng-click="AcceptInterview(DemoForm)">
Accept
</button>
</div>
OR you could do this:-
<body ng-app="app" ng-controller="DemoController">
<div class="container" ng-form="DemoForm">
<div class="row">
<div class="col-md-6">
<label>Is Interview Date Accepted: </label>
<input type="checkbox" class="AcceptedChecks" name="InterviewAccepted" ng-model="Interview.InterviewAccepted" ng-required="1 && !Interview.AlternateAccepted" ng-click="SetCheckDatesCount()" />
</div>
<div class="col-md-6">
<label>Is Alternate Date Accepted: </label>
<input type="checkbox" class="AcceptedChecks" name="AlternateAccepted" ng-model="Interview.AlternateAccepted" ng-required="1 && ! Interview.InterviewAccepted" ng-click="SetCheckDatesCount()" />
</div>
</div>
<div class="row">
<button class="btn btn-success" ng-click="AcceptInterview(DemoForm)">
Accept
</button>
</div>
</div>
</body>
</html>
<script>
// Code goes here
var app = angular.module("app", []);
app.controller("DemoController", ["$scope", function($scope){
$scope.showMessages = false;
$scope.Interview = {
AlternateAccepted: false,
InterviewAccepted: false
};
$scope.AcceptInterview = function (theForm) {
console.log(theForm.$invalid);
if (theForm.$invalid) {
$scope.showMessages = true;
return;
}
alert("valid");
}
}]);
</script>

how to remove the value of an input field using angularjs

<div class="info-block" ng-app="">
<div ng-controller="Note">
<div class="checkbox">
<label>
<p><b>Primary Publication: </b>
{{ form_widget(form.input_ppubs, { 'attr': {'class': 'valOption'}}) }}
</p>
</label>
</div>
<div ng-repeat="item in items">
<input type="text" placeholder="new input" ng-model="item.primaryPub">
</div>
<button type="button" ng-click="add()">New Item</button>
</div>
I am trying to retrieve the value of the html input field and remove it from input upon a button click
I am able to get the code, but I don't know how to remove the code.
var Note = function($scope){
$scope.items = [];
$scope.add = function () {
//angular way of implementing document.getElementByID();
pub1 = angular.element('#form_input_ppubs').val();
$scope.items.push({
primaryPub: pub1
});
};
}
You don't have to retrieve your items like this. It's ugly and not the angular way. angular.element('#form_input_ppubs').val();
Instead, simply reference it in your input using ngModel.
Declare it in your scope.
$scope.inputItem = null;
HTML
<input ng-model="inputItem " />
Use it in your function:
$scope.addItem = function(item) {
$scope.items.push(item);
//reset the model
$scope.inputItem = null;
}
Call it using ng-click
<button type="button" ng-click="addItem(inputItem)">Add Item</button>
If you do:
console.log($scope.items);
You should see an entry for primaryPub, the model for your input. Then you can target it by nulling the model, so:
$scope.items.primaryPub = null;
However you're using this inside an ng-repeat:
<div ng-repeat="(i, item) in items">
<input type="text" placeholder="new input" ng-model="items[i].primaryPub">
</div>
So your console.log (if you have more than one item in 'items') should show an array-like structure for primaryPub.

ngRepeat and checkbox

I have a div with ng-repeat:
<div ng-repeat="fruit in fruits">
<input type="checkbox" ng-model="this.value" ng-checked="false">{{fruit.code}} - {{fruit.short_name}}
</div>
Here furits is array object and which contains the field code, short_name.
furits: {
{
code : code_value1,
short_name :short_name_value1
},
{
code : code_value2,
short_name :short_name_value2
},...
{
code : code_value..,
short_name :short_name_value..
},
}
I would like to get the code of checked checkbox after submit button click and insert those codes in new array.
And also send the same array to server to complete the task.
Please help me to solve this issue.
<div ng-repeat="fruit in fruits">
<input type="checkbox" ng-model="fruit.isSelected" />{{fruit.code}} - {{fruit.short_name}}
</div>
<input type="button" ng-click="sendServer()" value="Submit" />
And your controller methods are like ,
$scope.sendServer = function(){
$scope.checkedFruits = [];
for(i = 0; i < $scope.fruits.length; ++i){
if ($scope.fruits[i].isSelected)
$scope.checkedFruits.push(fruit.code);
}
$scope.postData();
}
//Send array to server via web service with parameter FruitsCode
$scope.postData = function () {
$http.post('http://your.webservice/', {FruitsCode:$scope.checkedFruits}).success(
function(data){
$scope.response = data
})
}
Hopes this will help you !
<div ng-repeat="fruit in fruits">
<input type="checkbox" ng-model="fruit.isChecked" />{{fruit.code}} - {{fruit.short_name}}
</div>
<input type="button" ng-click="save()" value="SAVE" />
And inside your controller :
$scope.save = function(){
var myFruits = [];
for(i = 0; i < $scope.fruits.length; ++i){
if ($scope.fruits[i]. isChecked)
myFruits.push(fruit.code);
}
}

ngModel data binding is not working properly

I am using ngSwitch directive to switch the view to Edit the div content. HTML is as follows -
<div ng-switch="isEditing" ng-controller="descController">
<div ng-switch-when="true">
<textarea name="Name" rows="8" class="form-control" ng-model="desc"></textarea>
<button class="btn btn-primary" ng-click="saveEdit($parent)">Save</button>
<button class="btn btn-warning" ng-click="cancelEdit($parent);">Cancel</button>
</div>
<div ng-switch-default>
<p class="lead" >{{desc}}</p>
<p><button class="btn btn-mini btn-danger" ng-click="$parent.isEditing = true;">Edit</button></p>
</div>
</div>
The controller code is as follows
home.controller("descController", function($scope, Desc){
(function getAboutMe(){
Desc.getAboutMe().success(function(about){
$scope.desc = about[0].description;
$scope.actualText = about[0].description;
$scope.saveEdit = function($parent){
//$scope.desc = $scope.desc;
$parent.isEditing = false;
}
$scope.cancelEdit = function($parent){
$scope.desc = $scope.actualText;
$parent.isEditing = false;
};
}).error(function(err){
alert(err);
});
})();
});
What I am trying to do is, when the cancel button is pressed I want the original text to be visible on the div and when the save button is clicked I want the new text to be visible on the div. How can i achieve this? I am new to Angular.
Do you need something like this?
$scope.saveEdit = function($parent){
$scope.actualText = $scope.desc; //update actualText before switching to view mode
$parent.isEditing = false;
}
$scope.cancelEdit = function($parent){
$scope.desc = $scope.actualText; //restore des
$parent.isEditing = false;
};
The main problem is ng-switch creates a new scope. Therefore you need to bind to the parent scope in your textarea using $parent:
<textarea name="Name" rows="8" class="form-control" ng-model="$parent.desc"></textarea>
DEMO

Resources