make a list of infos adding Id in angularjs - angularjs

I want to make list of infos inputing Name, Work. THere is a form with those inputs. Putting Name and Work when SAVE button clicked, it will add to the list. and view them. But I also want to add id every time. How can I do this?
here is my plunker: https://plnkr.co/edit/VDYYrxk8Bz5KIoI0HFV4?p=preview
HTML:
<body ng-controller='MyController'>
<!-- <button ng-click='toggleForm()'>Upload</button> -->
<div>
<table class='table'>
<tr>
<th>Title</th>
<th>Work</th>
</tr>
<tr ng-repeat='info in infos'>
<td>{{info.name}}</td>
<td>{{info.work}}</td>
</tr>
</table>
</div>
<form class='form'>
<div class='form-group'>
<label>Name</label>
<input class='form-control' type="text" ng-model='info.name'>
</div>
<div class='form-group'>
<label>Work</label>
<input class='form-control' type="text" ng-model='info.work'>
</div>
<div class='form-group'>
<button class='btn btn-primary' ng-click='addInfos()'>Save</button>
</div>
</form>
</body>
script::
angular
.module('app')
.controller('MyController', function($scope){
// $scope.displayForm = false;
// $scope.toggleForm = function(){
// $scope.displayForm = !$scope.displayForm;
// };
$scope.infos = [];
// var currIndex = 0;
$scope.addInfos = function () {
$scope.infos.push({
name: '',
work: ''
// id: currIndex++
});
// $scope.infos.push(obj.info);
};
})

$scope.addInfos = function () {
$scope.infos.push({
name: $scope.info.name,
work: $scope.info.work,
id: $scope.infos.length + 1 // assuming you want ids to start with 1
});
$scope.info = {}; // to clear the form fields once an input is pushed to the array
};

Related

How to get selected option value from dropdown using angular

I have two drop downs with add resource button, when I click add resource button I need to pass selected option values from drop downs into insertResource method.How to get selected option value??I know we can easily do it using option:selected in jquery But I want do it in angular.Any help?
<body ng-app="intranet_App" ng-controller="myCtrl" ng-init="init()">
<div class="container">
<div class="row">
<div>
<label class="displayBlock margin">Project Name</label>
<input type="text" name="name" class="currentProjectName">
</div>
<div>
<label class="displayBlock margin">Resource Name</label>
<select name="ResourceInsert" id="allocateResource"><option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option></select>
</div>
<div>
<label class="displayBlock margin">Role Name</label>
<select name="ResourceInsert" id="allocateRole"><option data-ng-repeat="data in roleList" value="{{data.RoleId}}">{{data.RoleName}}</option></select>
</div>
</div>
<div class="row">
<button class="btn btn-primary addResource" ng-click="insertResource()">Add Resource</button>
</div>
</div>
</body>
<script>
var app = angular
.module('intranet_App', [])
.controller('myCtrl', function ($scope,$http) {
$scope.init = function () {
$scope.getProjId();
$scope.ResourceJson();
$scope.RoleJson();
}
$scope.getProjId = function () {
var url = document.URL;
var id = decodeURI(/id=([^&]+)/.exec(url)[1]);
var projectName = decodeURI(/val=([^&]+)/.exec(url)[1]);
$('.currentProjectName').val(projectName)
}
$scope.ResourceJson = function () {
$http.post('/Project/empList').then(function (response) {
$scope.resourceList = response.data;
console.log($scope.resourceList)
})
}
$scope.RoleJson = function () {
$http.post('/Project/roleList').then(function (response) {
$scope.roleList = response.data;
console.log($scope.roleList)
})
}
$scope.insertResource = function () {
}
});
</script>
If your questions is getting data of selected item of select. It is done as follows using ng-model directive:
<select name="ResourceInsert" id="allocateResource" ng-model="selectedValue">
<option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option>
</select>
In Controller:
console.log($scope.selectedValue, "selected Value"); //Your selected value which is EmpId.

Angularjs cannot perform crud operations from accordion

I am trying to add a form to a bootstrap accordion and post a text value. Without accordion the form works alright. When i added the form to the accordion i am not able to pass text box value to angularjs controller. Basically i am not able to perform the CRUD operations as i am not able to pass the values. Minimum code related to the issue.
main.html
<div ng-controller="myController">
<accordion class="accordion" close-others="oneAtATime">
<accordion-group ng-repeat="group in groups" is-open="status.isOpen[$index]" >
<accordion-heading>
{{group.groupTitle}} <i class="fa chevron-icon" ng-class="{'fa-chevron-down': status.isOpen[$index], 'fa-chevron-right': !status.isOpen[$index]}"></i>
</accordion-heading>
<div ng-include="group.templateUrl"></div>
</accordion-group>
</accordion>
</div>
controller.js
App.controller('myController', ['$scope', 'Parts', function($scope, Parts) {
var original = $scope.parts;
$scope.submit = function() {
if ($scope.parts.a_id == null) {
$scope.createNewPart();
} else {
$scope.updatePart();
}
};
$scope.createNewPart = function() {
Parts.resource1.create($scope.parts);
};
$scope.updatePart = function() {
Parts.resource2.update($scope.parts)
};
$scope.oneAtATime = true;
$scope.groups = [{
groupTitle: "ADD 1",
templateUrl: "file1.html"
}, {
groupTitle: "ADD 2",
templateUrl: "file2.html"
}];
$scope.status = {
isOpen: new Array($scope.groups.length)
};
for (var i = 0; i < $scope.status.isOpen.length; i++) {
$scope.status.isOpen[i] = (i === 0);
}
} ]);
file1.html
<div>
<form name="myForm" ng-submit="submit()">
<div class="row">
<label class="col-md-2 control-lable" for="part">Add1</label>
<input type="text" ng-model="parts.part" id="part" required />
</div>
<div class="row">
<input type="submit" value="{{!parts.id ? 'Add' : 'Update'}}" ng-disabled="myForm.$invalid">
</div>
</form>
//inside table
<tr ng-repeat="a in availableparts >
<td>{{a.id}}</td>
<td>{{a.apart}}</td>
<td><button type="button" ng-click="editPart(a.id)" >Edit</button>
<button type="button" ng-click="deletePart(a.id)">Remove</button>
</td>
</tr>
</div>
Initially, you need to set $scope.parts to empty object {}, so when you access $scope.parts.id you will have null, instead of error saying id of undefined

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].

dynamically create add form clicking add button in angularjs

I want to create dynamic form field after i clicked to add row button.
<form name="form" class="form-validation form-inline" >
<div class="form-group">
{!!
Form::text('name',null,['class'=>'form-control','placeholder'=>'Name','data-ng-model'=>'name','required'=>'required'])
!!}
{!!
Form::text('description',null,['class'=>'form-control','placeholder'=>'Description','data-ng-model'=>'description'])
!!}
</div>
<div class="form-group">
<button class="btn btn-default " ng-disabled="form.$invalid"
data-ng-click="addTag()">
Add
</button>
</div>
Add row
<div ng-repeat="input in form">
<form name="form" class="form-validation form-inline">
<div class="form-group">
{!!
Form::text('name',null,['class'=>'form-control','placeholder'=>'Name','data-ng-model'=>'input.name','required'=>'required'])
!!}
{!!
Form::text('description',null,['class'=>'form-control','placeholder'=>'Description','data-ng-model'=>'input.description'])
!!}
</div>
<div class="form-group">
<button class="btn btn-default " ng-disabled="form.$invalid"
data-ng-click="addTag()">
Add
</button>
</div>
</form>
</div>
And the controller section is like after edited.
How should i add them in to database?
Angularjs controller:
$scope.addTag = function () {
var tag = {
name: $scope.name,
description: $scope.description
};
$http.post('tags', tag)
.success(function (data) {
console.log('www.sabin.info.np');
$scope.tags = data;
$scope.name = '';
$scope.description = '';
}).error(function (err) {
console.log('error');
});
};
and the code that i have edited is:
$scope.form = [];
$scope.addRow = function() {
$scope.form.push({
name: '',
description: ''
});
}
add row field
First you need to initialize the scope of the input form by specifying an array of object. Ex:
$scope.form = [];
After that, simply add this function to your controller :
$scope.addRow = function() {
$scope.form.push({
name: '',
description: ''
});
}
And use ng-repeat to iterate the form
<div ng-repeat="input in form">
<input ng-model="input.name" />
<input ng-model="input.description" />
</div>
[UPDATED]
So, I supposed you want to send the data that was inputed in each row to the backend with the endpoint of /tags. Here's how:
Actually all the form data was stored in $scope.form, which is an array of object with name and description attributes inside each of the object. So if you want to access the name/description value of the first row, you can access the value through $scope.form[0].name and $scope.form[0].description.
So the right method of sending the data is :
In HTML:
<div ng-repeat="input in form">
<input ng-model="input.name" />
<input ng-model="input.description" />
//You pass the input object throught the function params
<button ng-click="addTag(input)">Add Tag</button>
</div>
In Controller :
$scope.addTag = function (input) {
$http.post('tags', input)
.success(function (data) {
console.log('www.sabin.info.np');
}).error(function (err) {
console.log('error');
});
};

AngularJS - Using ng-repeat twice under the same controller

I have the following DIV:
<div ng-controller="userControl">
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select name="userSelect">
<div ng-repeat="user in users">
<option value="{{user.id}}">{{user.name}}</option>
</div>
</select>
<input type="submit" value="add">
</form>
</div>
This is my controller:
function userControl($scope,$http) {
$scope.users = [
{"id":"0","name":"Username1","roles":[{}]},
{"id":"1","name":"Username2","roles":[{}]},
]
$scope.addUser = function() {
var nextid = $scope.getNextId();
$scope.users.push({id:nextid,name:$scope.userName});
/*
$.post({}); //Push changes to server
*/
$scope.userName = '';
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
I can see the first ng-repeat is working fine and is listing the user.id and user.name, however the second ng-repeat (the one inside the form) does not display the information, is that related to the fact that I've already looped through that element in the previous div?
You misused the select directive :
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users">
http://docs.angularjs.org/api/ng.directive:select

Resources