Push empty row with input field using angularjs - angularjs

I have one table which have edit, delete and add options. My problem is when I click on add button want to add row with empty input fields. I have write below code for this. What should I do to add empty row with empty input values.
My code
<div ng-controller="AppKeysCtrl">
<button ng-click="add()">
Add
</button>
<table class="table table-hover mytable">
<thead>
<tr>
<th></th>
<th>Created</th>
<th>App Key</th>
<th>Name</th>
<th>Level</th>
http://jsfiddle.net/Thw8n/155/#update <th>Active</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="entry in appkeys" data-ng-class="{danger:!entry.active}">
<td>{{$index + 1}}</td>
<td>{{entry.timestamp | date:'mediumDate'}}</td>
<td>{{entry.appkey}}</td>
<td>
<span data-ng-hide="editMode">{{entry.name}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="entry.name" data-ng-required />
</td>
<td>
<span data-ng-hide="editMode">{{entry.level}}</span>
<select class="form-control" name="entry.level" data-ng-model="entry.level" data-ng-show="editMode">
<option value="3">3 - Developer Access - [Temporary]</option>
<option value="2">2 - Standard Tool Access - [Default]</option>
<option value="1">1 - Administrative Access - [Admin Section Only]</option>
</select>
</td>
<td>
<span data-ng-hide="editMode">{{entry.active && 'Active' || 'Inactive'}}</span>
<select class="form-control" name="entry.active" data-ng-model="entry.active" data-ng-show="editMode">
<option value="true">Active</option>
<option value="false">Inactive</option>
</select>
</td>
<td>
<button type="submit" data-ng-hide="editMode" data-ng-click="editMode = true; editAppKey(entry)" class="btn btn-default">Edit</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false" class="btn btn-default">Save</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false; cancel($index)" class="btn btn-default">Cancel</button>
</td>
</tr>
</tbody>
</table>
<pre>newField: {{newField|json}}</pre></br></br>
<pre>appkeys: {{appkeys|json}}</pre>
</div>
app = angular.module("formDemo", []);
function AppKeysCtrl($scope, $http, $location) {
var tmpDate = new Date();
$scope.newField = [];
$scope.editing = false;
$scope.appkeys = [
{ "appkey" : "0123456789", "name" : "My new app key", "created" : tmpDate },
{ "appkey" : "abcdefghij", "name" : "Someone elses app key", "created" : tmpDate }
];
$scope.editAppKey = function(field) {
$scope.editing = $scope.appkeys.indexOf(field);
$scope.newField[$scope.editing] = angular.copy(field);
}
$scope.saveField = function(index) {
//if ($scope.editing !== false) {
$scope.appkeys[$scope.editing] = $scope.newField;
//$scope.editing = false;
//}
};
$scope.cancel = function(index) {
//if ($scope.editing !== false) {
$scope.appkeys[index] = $scope.newField[index];
$scope.editing = false;
//}
};
$scope.add = function () {
var entry = {};
//$scope.goals.push(goal);
$scope.appkeys.push(entry);
};
}
angular.element(document).ready(function() {
angular.bootstrap(document, ["formDemo"]);
});
I have problem in this that when I click on add empty row is adding which have form fields with ng-hide attribute. I want to add row dynamically with new input boxes for each column. What should I do for this? Please help.

It's quite simple. You need to push an object with blank value into your array.
Below is the code:
Controller
$scope.add = function () {
$scope.appkeys.push({appkey : '', name : '', created : '' });
};
The above code will only add a row. I have updated your JSFiddle for your desired output.
Please go through with the given link.
http://jsfiddle.net/Thw8n/570/

You need to paste the following code:
$scope.add = function () {
$scope.appkeys.push({appkey : '', name : '', created : '' });
};

You can push object with empty properties in your appkey array:
var tempObject = {
"appkey":"",
"name":"",
"created":""
};
$scope.appkeys.push(tempObject);

Related

Problem for using a textbox and radio buttons in order to filter a table in ng-reapeat Angularjs

I have a problem for filtering a table in AngularJS into ng-repeat.
I would like to add radio button (based on table column) under a search text field for adding more filters.
For the moment when I enter "char" in the text field, the system filters correctly the table and displays all results.
My goal: if I select the radio button "Person", only the results with the person containing "char" should appear. If I click on "company", the radio button "Person" should be unselected and only result with the company containing "char" should appear.
Here my view:
<div class="spacer input-group">
<div class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</div>
<input type="text" ng-model="searchText" class="form-control" placeholder="Search name..." ng-change="search(searchText)"/>
<div class="input-group-btn">
<button class="btn btn-default" ng-click="razRecherche()">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div>
</div>
<div>
<!-----------------HERE THE RADIO BUTTONS ----------- START --->
<input type="radio" name="filter" value="PERSON" ng-model="search.PERSON">
<label for="PERSON">Person</label>
<input type="radio" name="filter" value="COMPANY" ng-model="search.COMPANY">
<label for="COMPANY">Company</label>
<!-----------------HERE THE RADIO BUTTONS ------------- END --->
</div>
<div class="table-responsive" id="allContacts">
<table ng-show="contacts.length" class="table table-striped table-hover spacer">
<thead>
<tr>
<th class="colPerson">
Person
<span class="hSpacer" ng-class="cssChevronsTri('PERSON')"></span>
</th>
<th class="colCompany">
Company
<span class="hSpacer" ng-class="cssChevronsTri('COMPANY')"></span>
</th>
<th class="colDescription">
Description
<span class="hSpacer" ng-class="cssChevronsTri('REQUESTDESCRIPTION')"></span>
</th>
</tr>
</thead>
<tbody ng-repeat="contact in contacts | filter:searchText | orderBy:champTri:triDescendant">
<tr class="clickable">
<td class="colPerson" ng-click="selContact(contact,contact.ID)" ng-class="{sel:selIdx==$index}">{{contact.PERSON}}</td>
<td class="colCompany" ng-click="selContact(contact,contact.ID)">{{contact.COMPANY}}</td>
<td class="colDescription" ng-click="selContact(contact,contact.ID)">{{contact.REQUESTDESCRIPTION}}</td>
</tr>
</tbody>
</table>
</div>
My controller
app.controller('ctrlContacts', function ($scope, $timeout, ContactService){
$scope.search = function(searchText) {
$scope.reloadPreviousSearch = false;
if (!searchText.length) {
//alert("searchText empty");
}
if (searchText.length>2) {
$timeout(function () {
// RETRIEVE DATA FROM JSON OBJECT OF THE SERVER SEVICE AND A DB QUERY - OK
ContactService.fastSearch(searchText).success(function(contacts){
console.log("query fastSearch OK");
var length = contacts.length;
$scope.loading = false;
if (length == 0) {
$scope.searchButtonText = "No result";
}else {
$scope.searchButtonText = length + " results found";
}
// For the orderby date
for (var i=0; i<length; i++) {
if(contacts[i].REQUESTTRUEDATE!=""){
contacts[i].REQUESTTRUEDATE = new Date(contacts[i].REQUESTTRUEDATE.replace(/-/g,"/"));
}else{
contacts[i].REQUESTTRUEDATE=null;
}
}
$scope.contacts = contacts;
$scope.champTri='PERSON';
$scope.selIdx= -1;
$scope.selContact=function(contact,idx){
$scope.selectedContact=contact;
$scope.selIdx=idx;
window.location="#/view-contacts/" + idx;
}
$scope.isSelContact=function(contact){
return $scope.selectedContact===contact;
}
});
}, 1000);
}else{
$scope.contacts=null;
}
}
// SEARCH
$scope.searchText = null;
$scope.razRecherche = function() {
$scope.searchText = null;
$scope.contacts=null;
}
// SORT
$scope.champTri = null;
$scope.triDescendant = false;
$scope.personsSort = function(champ) {
if ($scope.champTri == champ) {
$scope.triDescendant = !$scope.triDescendant;
} else {
$scope.champTri = champ;
$scope.triDescendant = false;
}
}
$scope.cssChevronsTri = function(champ) {
return {
glyphicon: $scope.champTri == champ,
'glyphicon-chevron-up' : $scope.champTri == champ && !$scope.triDescendant,
'glyphicon-chevron-down' : $scope.champTri == champ && $scope.triDescendant
};
}
});
I'm trying to add the radio buttons for filtering the table from the text entered in the text field. But I don't know how to use them for filtering the table into the ng-repeat.
Could you please help me to add the filters on the text field (searchText) with the radio buttons?
Thank you in advance for your help.
you have to make the following edits:
Edit your radio buttons as follow :
<!-----------------HERE THE RADIO BUTTONS ----------- START --->
<input type="radio" name="filter" value="PERSON" ng-change ="chosefilter()"
ng-model=" filterType">
<label for="PERSON">Person</label>
<input type="radio" name="filter" value="COMPANY" ng-change ="chosefilter()"ng-model="filterType">
<label for="COMPANY">Company</label>
<!-----------------HERE THE RADIO BUTTONS ------------- END --->
your table as follow :
<tbody ng-repeat="contact in contacts | filter:searcher| orderBy:champTri:triDescendant">
inside your controller add this:
$scope.searchText="";
$scope.searcher={
PERSON:"",
COMPANY:"",
};
$scope.filterType="PERSON";
$scope.chosefilter=function()
{
console.log( $scope.filterType);
if( $scope.filterType=='PERSON')
{
$scope.searcher.PERSON=$scope.searchText;$scope.searcher.COMPANY="";
}
else if( $scope.filterType=='COMPANY')
{
$scope.searcher.COMPANY=$scope.searchText;$scope.searcher.PERSON="";
}
console.log($scope.searcher);
}
what i did that $scope.searcher variable must has properties the same as data content properties like PERSON and COMPANY . then in filter just write the name of the object like this : filter:[OBJECT NAME] ;
i did a small app to make your filter , so if there is errors please tell me to fix it .

Show button on change ng-model AngularJS

I want to show button post only when modelCheck will change.
My code :
HTML :
<table>
<tr>
<th>name</th>
<th><button class="btn" ng-if="modelCheck === {}" ng-click="post()">post</button></th>
<th><button class="btn disabled" ng-if="modelCheck !== {}" ng-click="post()">post</button></th>
</tr>
<tr ng-repeat="x in messages">
<td>{{x.name}}</td>
<td><input type="checkbox" ng-model="modelCheck[x.name]"/></td>
</tr>
</table>
JS:
$scope.modelCheck = {};
$scope.messages =
[
{
"name": "eva",
},
{
"name": "ben",
},
];
$scope.post = function(){
var data = [];
for (var k in $scope.modelCheck) {
if ($scope.modelCheck.hasOwnProperty(k) && $scope.modelCheck[k]) {
data.push({'name': k});
}
}
console.log(data);
// do with data as you wish from here
};
Plunker:http://next.plnkr.co/edit/xQ3AGFW03qGWKyxI
My code doesn't work. Thanks for answers and help in advance!
use this condition to check the empty object
<th><button class="btn" ng-if="(modelCheck | json) != ({} | json)" ng-click="post()">post</button></th>

How can I pass a Camunda process variable containing JSON from one form to the next?

I want to get json array Data from service and then display this data inside table (with checkboxes)
after that i want to get data ( which was checked by user , i mean checkbox was clicked) and put it another json Array and then wrap this variable as camVariable in order to export it for second user form,
i have tried this in several ways but can’t accomplish my goal, what should i change to make it possible?
here is my code:
camForm.on('form-loaded', function() {
camForm.variableManager.fetchVariable('jsonData');
});
camForm.on('variables-fetched', function() {
$scope.jsonData = camForm.variableManager.variableValue('jsonData');
});
var selectedDocuments=$scope.selectedDocuments=[];
$scope.content = '';
$scope.isChecked = function(id){
var match = false;
for(var i=0 ; i < $scope.selectedDocuments.length; i++) {
if($scope.selectedDocuments[i].id == id){
match = true;
}
}
return match;
};
$scope.sync = function(bool, item){
if(bool){
// add item
$scope.selectedDocuments.push(item);
} else {
// remove item
for(var i=0 ; i < $scope.selectedDocuments.length; i++) {
if($scope.selectedDocuments[i].id == item.id){
$scope.selectedDocuments.splice(i,1);
}
}
}
};
camForm.on('submit', function() {
camForm.variableManager.createVariable({
name: 'selectedDocuments',
type: 'json',
value:$scope.selectedDocuments
});
});
function toJsonValue(arr) {
var myJSON = "";
var FinalResult = JSON.stringify(arr);
myJSON = JSON.stringify({FinalResult});
var json=$scope.json={};
json=JSON.parse(myJSON);
return json;
}
$scope.toggle = function (index){
if($scope.jsonData[index].hidethis == undefined){
$scope.jsonData[index].hidethis = true;
}else{
$scope.jsonData[index].hidethis = !$scope.jsonData[index].hidethis;
}
}
</script>
<h2>My job List</h2>
<div class="container">
<table name ="table" class="table table-hover" style="width:100%;" cellspacing="0">
<thead>
<tr>
<th style="width:80px; height:25px;"><input style="width:25px; height:25px;" type="checkbox" onclick="checkAll(this)"></th>
<th style="width:140px;">id</th>
<th style="width:305px;">organizationNameEN</th>
<th style="width:305px;">organizationNameGE</th>
<th> </th>
</tr>
</thead>
<tbody ng-repeat="item in jsonData" >
<tr>
<td><input type="checkbox" ng-change="sync(bool, item)" ng-model="bool" ng-checked="isChecked(item.id)" ></td>
<td><input style="width:305px;" type="number" id="id" ng-model="item.id" readonly /></td>
<td><input style="width:305px;" type="text" id="organizationNameEN" ng-model="item.organizationNameEN" required /></td>
<td><input style="width:305px;" type="text" id="organizationNameGE" ng-model="item.organizationNameGE" required/></td>
<td><button class="btn btn-default btn-xs" ng-click="toggle($index)"><span class="glyphicon glyphicon-eye-open"></span></button></td>
</tr>
<tr id="{{hideid + $index}}" ng-show="item.hidethis">
<td>
<label for="startDate" class="control-label">startDate</label>
<div class="controls">
<input style="width:105px;" id="strtDate" class="form-control" type="text" ng-model="item.startDate" required readonly/>
</div>
<br>
<label for="endDate" class="control-label">endDate</label>
<div class="controls">
<input style="width:105px;" id="endDate" class="form-control" type="text" ng-model="item.endDate" required readonly/>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script>
function checkAll(bx) {
var cbs = document.getElementsByTagName('input');
for(var i=0; i < cbs.length; i++) {
if(cbs[i].type == 'checkbox') {
cbs[i].checked = bx.checked;
}
}
}
</script>
</form>
I do something similar. In my first form, the user captures some transactions. Form 2 they double-capture (new transactions which must match the first capture) and form 3 they view they successful transactions and authorise them.
I have handled this by creating a JSON array of transactions in the first form. I save this to a process variable in the on-submit event using code like this:
camForm.on('submit', function() {
// this callback is executed when the form is submitted, *before* the submit request to
// the server is executed
// creating a new variable will add it to the form submit
variableManager.createVariable({
name: 'customVariable',
type: 'String',
value: 'Some Value...',
isDirty: true
});
I retrieve it in the subsequent forms like you do in the form-loaded/variables-fetched events.
If the JSON array data is updated in subsequent forms, I save it back to the same variable using code like this:
camForm.on('submit', function(evt) {
var fieldValue = customField.val();
var backendValue = variableManager.variable('customVariable').value;
if(fieldValue === backendValue) {
// prevent submit if value of form field was not changed
evt.submitPrevented = true;
} else {
// set value in variable manager so that it can be sent to backend
variableManager.variableValue('customVariable', fieldValue);
}
});
These code snippets are from the Camunda documentation.

AngularJS NG-Repeat Select and set selected on page load?

I am generating a grid thru Angular and each row will have a dropdown. I want the dropdown to populate with data from the server which is working but during page load, it needs to set the selected item of each dropdown to the value of the property it's bound to. Simple example below...
Class CategoryField
ID
Name
CategoryID = 2
Select
Option1 text=Category A value=1
Option2 text=Category B value=2 <--- This item should be selected on load.
The code i have appears to have a selected attribute on an item in each dropdown from page source but the dropdown is loading and selecting the blank item angular adds. Code below for grid...UPDATED CODE BELOW
<div ng-app="CategoryFieldsApp">
Search:<input ng-model="search" type="text" placeholder="Search" />
#using (Html.BeginForm("CategoryFields", "Maintenance", FormMethod.Post))
{
<div ng-controller="CategoryFieldsCtrl">
<table class="table table-striped table-hover">
<thead>
<tr>
<th></th>
<th width="200">Category</th>
<th ng-click="sort('Name')" width="200">Name</th>
<th width="150">Active</th>
</tr>
</thead>
<tbody id="CategoryFieldGrid">
<tr dir-paginate="categoryField in categoryFields|orderBy:sortKey:reverse|filter:search|itemsPerPage:10">
<td>
<input type="hidden" name="CategoryFields[{{$index}}].CategoryFieldID" ng-model="categoryField.CategoryFieldID" />
</td>
<td>
<input class="hdnCategoryID" type="hidden" name="CategoryFields[{{$index}}].CategoryID" />
<select ng-model="categoryField.CategoryID" ng-options="category.CategoryID as category.Name for category in categories"></select>
</td>
<td>
<input type="text" name="CategoryFields[{{$index}}].Name" ng-model="categoryField.Name" />
</td>
<td>
<input type="checkbox" class="active checkBox checkbox-inline" value="{{categoryField.Active}}" ng-model="categoryField.Active" name="CategoryFields[{{$index}}].Active" />
</td>
<td>
<input type="button" ng-click="remove($index)" value="Remove" />
</td>
</tr>
</tbody>
</table>
<dir-pagination-controls max-size="5"
direction-links="true"
boundary-links="true">
</dir-pagination-controls>
<br />
<a class="btn btn-default" ng-click="add()">Add Category Field</a>
<input class="btn-primary btn-sm" type="submit" value="Save" />
</div>
}
<script>
var App = angular.module('CategoryFieldsApp', ['angularUtils.directives.dirPagination']).controller('CategoryFieldsCtrl', function ($scope, $http) {
$http.get("#Url.Action("GetCategoryFields", "Maintenance")").success(function (response) {
$scope.categoryFields = response; //ajax request to fetch data into $scope.data
});
$http.get("#Url.Action("GetCategories", "Maintenance")").success(function (response) {
$scope.categories = response; //ajax request to fetch data into $scope.data
});
$scope.sort = function (keyname) {
$scope.sortKey = keyname; //set the sortKey to the param passed
$scope.reverse = !$scope.reverse; //if true make it false and vice versa
}
$scope.remove = function (index) {
$scope.categoryFields.splice(index, 1);
};
$scope.add = function () {
$scope.categoryFields.push({
CategoryFieldID: 0,
CategoryID: 0,
Name: '',
Active: true,
ShowRemove: true
});
};
});
//$(document).ready(function () {
// $('#CategoryFieldGrid tr').each(function (i, row) {
// var categoryID = $(row).find('.hdnCategoryID').val();
// console.log(categoryID);
// $(row).find('.ddlCategories').val(categoryID);
// });
// $('.ddlCategories').on('change', function (e) {
// var hidden = $(e.target).closest('tr').find('.hdnCategoryID');
// $(hidden).val($(e.target).closest('tr').find('.ddlCategories').val());
// });
//});
Have you considered using ng-options? It could be used to replace the explicit definition of your options:
<select ng-model="categoryField.CategoryID" ng-options="category.CategoryID as category.Name for category in categories"></select>
if you break down the expression we pass to ng-options, we're setting the value of the selected item to the CategoryID property, the visible name of each option to the category Name property, and we're passing in all the categories defined $scope.categories as options:
"category.CategoryID as category.Name for category in categories"
Here's a working example I put together: http://plnkr.co/edit/CXZaUYfqcIv7PbeUrT9j?p=preview
I was able to figure out the other side of the bindings so that the mvc model was updated for post back. I simply created a hidden field that was bound to the same property. When angular's ng-model updates, it updated the value of the hidden field also. Below is the syntax for those who needs it.
<input class="hdnCategoryFieldID" type="hidden" name="CategoryFieldApprovers[{{$index}}].CategoryFieldID" value="{{categoryFieldApprover.CategoryFieldID}}" />
<select ng-model="categoryFieldApprover.CategoryFieldID" ng-options="categoryField.CategoryFieldID as categoryField.Name for categoryField in categoryFields"></select>

Cannot delete element using AngularFire $remove()

I am attempting to remove an item (round) from my DB. I can console.log the $id but when I try to roundsList.$remove(round.id) it does not do anything. I am, once again, thoroughly confused...
JS:
.controller('RoundsCtrl', ['$scope', '$firebase', 'FBURL', function ($scope, $firebase, FBURL, url) {
var roundsRef = new Firebase(FBURL + 'rounds');
var roundsList = $firebase(roundsRef).$asArray();
var usersRef = new Firebase(FBURL + 'users');
var usersRef = usersRef.child($scope.loggedInUserID).child('rounds');
var usersRounds = $firebase(usersRef).$asArray();
$scope.removeItem = function (index, round, event) {
// Avoid wrong removing
if (round.$id == undefined) return;
// Firebase: Remove item from the list
$scope.roundsList.$remove(round.$id);
};
/* SET DEFAULT FOR TOGGLE TO COLLAPSED*/
$scope.isCollapsed = true;
/* ONCE ROUNDS ARE LOADED RETURNS ROUNDS BY ID FOR INDIVIDUAL USER*/
usersRounds.$loaded()
.then(function (data) {
$scope.rounds = data.map(function (item) {
console.log(item);
console.log(item.$id);
return roundsList.$getRecord(item.roundID);
});
});}])
HTML:
<tbody ng-repeat="round in rounds | orderBy:orderBy">
<tr>
<td>
{{round.date}}
</td>
<td>
{{round.courseName}}
</td>
<td>
{{round.courseID}}
</td>
<td>
{{round.user}}
</td>
<td>
{{round.userID}}
</td>
<td>
{{round.tags}}
</td>
<td>
View
Edit
<button class="btn btn-danger" ng-click="isCollapsed = !isCollapsed">Delete</button>
</td>
</tr>
<tr collapse="isCollapsed">
<td colspan="7">
<div>
<div class="well well-lg">
<p>Are you sure? This cannot be undone!</p>
<button ng-click="removeItem($index, round, $event)" class="btn btn-danger">Delete Round</button>
<button ng-click="isCollapsed = !isCollapsed" class="btn btn-info">Cancel</button>
</div>
</div>
</td>
</tr>
</tbody>
EDIT:
I was finally able to delete from both DBs using the following code. hope it helps someone else down the line.
/* DELETES ROUND FROM MAIN ROUND DATABASE AND FROM USER SPECIFIC DB*/
var roundsListSync = $firebase(roundsRef);
var usersRoundsListSync = $firebase(usersRefRounds);
$scope.removeItem = function (index, round, event) {
roundsListSync.$remove(round.$id);
//console.log(usersRounds);
var i = 0;
var len = usersRounds.length;
for (; i < len;) {
console.log(usersRounds[i].roundID);
if (usersRounds[i].roundID === round.$id) {
var usersRoundsID = usersRounds[i].$id;
//console.log(usersRoundsID);
usersRoundsListSync.$remove(usersRoundsID);
i++;
} else {
i++;
}
}
};
You are calling $scope.roundsList.$remove(round.$id), however you have not declared roundsList in the scope: var roundsList = $firebase(roundsRef).$asArray(); Try var roundsList = $firebase(roundsRef).$asArray() instead.
If that doesn't work, try to make a firebase reference that is not an array:
var roundsListSync = $firebase(roundsRef);
roundsListSync.$remove(round.$id);

Resources