Automatically added ng-hide in a button - angularjs

<table>
<tr ng-repeat="response in customUserResponse">
<td>
<div class="buttons" align="center">
<button ng-disabled="isReadOnly" class="btn actionBtn edit-disable"
ng-click="editResponse($index)"><i class="fa fa-edit"></i></button>
<button ng-show="!response.Is_Global__c"
ng-model="response.Is_Global__c" ng-
disabled="isReadOnly" class="btn actionBtn edit-disable"
ng-click="deleteQuestion($index)">
<i class="fa fa-trash"></i></button>
</div>
</td>
</tr>
</table>
<table class="table" style="margin-top: 10px;">
<tr>
<td>
<button ng-disabled="isReadOnly" class="btn actionBtn"
ng-click="addUserRow()">
<i class="fa fa-plus"></i></button>
</td>
</tr>
</table>
$scope.addUserRow = function () {
var l = $scope.customUserResponse.length;
if(l==0)
{
l = $scope.customUserQuestion.length;
}
var quest = {Question_Text__c:"", Response_Value__c:"", Status__c:"", Comments__c:"",
Is_Global__c:"false", Order__c:l};
$scope.enabledEditResponse[l] = true;
$scope.customUserResponse.push(quest);
//var element = document.getElementByClass("deleteButton");
//element.classList.remove("ng-hide");
//angular.element(document.querySelector("#deleteButton")).removeClass("ng-hide");
//$scope.showDeleteBtn = true;
//$scope.$apply();
};
$scope.submitQuestion = function() {
var data = [];
if($scope.customUserResponse.length >= $scope.customUserQuestion.length)
data = data.concat($scope.customUserResponse);
else {
data = data.concat($scope.customUserQuestion);
data = data.concat($scope.customUserResponse);
}
data.forEach(function(element) { element.Application_Id__c = $scope.appId; });
var len = data.length;
for(var i=0; i<len;i++){
data[i].Order__c = i+1;
}
ApplicationDataSource.saveFundingChecklistResponse(angular.toJson(data), function (result) {
if(result[0] !='{\"error\": true, \"result\": null}')
{
$scope.getResponse($scope.loadResponseInTable);
alert('Data saved Successfully');
$scope.resetEnabledEditResponse();
//$scope.init();
}
else
{
alert('Something went wrong. Data is not saved.');
}
$scope.$apply();
});
};
When response.Is_Global__c == false, the delete button will show.
When I clicked plus button one row is added but the delete button doesn't show. But after saving both button shows. When I inspect the code, I see ng-hide is automatically added in the class and if I remove manually the ng-hide class then the button shows.

ng-hide class is added when ng-show expression evaluates to a falsy value:
This means that after the save action this expression becomes false:
!response.Is_Global__c
The element is shown or hidden by removing or adding the .ng-hide CSS class onto the element.
https://docs.angularjs.org/api/ng/directive/ngShow

Related

multiple filters in AngularJS with text and radio buttons

I'm doing a search module on a table. The search (text field) on the table is working. There are equally sorts on column header of the table.
I would like to add radio button under the search text field for improving my search (add filter).Hence the search will be based on the text entered for the field chosen.
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>
<div>HERE THE RADIO BUTTONS</div>
</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 my filter is not working.
Could you please help me to add the filters on the text field (searchText) with the radio button?
Thank you in advance for your help.
if I understand right you, you want create a multiple filter by radio buttons
filter property wants an object as parameter
for example you can make in this way:
ng-repeat="contact in contacts | filter:{firstnameProperty:firstnameParamenter, ageProperty:ageParameter}
where firstnameProperty is a property on your array object and firstnameParameter is a variable, such as $scope.firstnameParameter
and you can bind to an input.
instead of
ng-repeat="contact in contacts | filter:searchText

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.

Push empty row with input field using 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);

ng-repeat with controller for each table row: how do I access x-editable form elements?

I setting up a scenario very similar to the Editable Row example from the x-editable demo site. In this scenario, a there is a simple table with three columns for data and a fourth for edit and delete buttons. A third button outside of the table adds a row to the table. When the form is editable, the data columns become editable (the primary feature of x-editable library). For this demo, the first column becomes a simple text edit and the second two columns become drop lists.
The table is created by having an ng-repeat on a row template. I need to do a few different things that all involve accessing the scope created by the ng-repeat. I need to
detect when the row is editable and when it is not
filter the options for the second drop list when the first drop list changes
In order to try to work with this demo, I've added a controller for the individual row. That has given me some access to the form (name = rowform), but I'm still not able to set a watch on the "make" property. I can't even find what property of the form is changing when the user makes a selection.
How do I set up a watch on the 'make' property?
Page Controller
angular.module('app').controller("quoteBuckingRaterController",
function ($scope, $q, $filter, listService, transactionDataService) {
$scope.equipment = [];
$scope.makes = [];
$scope.models = [];
$scope.showModel = function(equip) {
if(equip.model) {
var selected = $filter('filter')($scope.models, {id: equip.model});
return selected.length ? selected[0].name : 'Not set';
} else {
return 'Not set';
}
};
$scope.showMake = function(equip) {
if (equip.model) {
var selected = $filter('filter')($scope.models, { id: equip.model });
if (selected.length && selected.length > 0) {
if (equip.make != selected[0].make)
equip.make = selected[0].make;
return selected[0].make;
}
else {
return 'Not set';
}
} else {
return 'Not set';
}
};
$scope.checkName = function (data, id) {
if (!data) {
return "Description is required";
}
};
$scope.checkModel = function (data, id) {
if (!data) {
return "Model is required";
}
};
$scope.saveEquipment = function (data, id) {
$scope.inserted = null;
};
$scope.cancelRowEdit = function (data, id) {
$scope.inserted = null;
};
$scope.removeEquipment = function(index) {
$scope.equipment.splice(index, 1);
};
$scope.addEquipment = function() {
$scope.inserted = {
id: $scope.equipment.length+1,
name: '',
make: null,
model: null
};
$scope.equipment.push($scope.inserted);
};
$scope.filterModels = function (make) {
$scope.models = _.where($scope.allModels, function(item) {
return item.make == make;
});
};
//called by another process when page loads
$scope.initialize = function (loaded) {
return $q(function (resolve, reject) {
if (!loaded) {
listService.getEquipmentModels().then(function (data) {
$scope.allModels = data;
$scope.models = data;
//uses underscore.js
$scope.makes = _.chain(data)
.map(function (item) {
var m = {
id: item.make,
name: item.make
};
return m;
})
.uniq()
.value();
resolve();
});
}
});
}
});
Row Controller
angular.module('app').controller("editRowController",
function ($scope) {
$scope.testClick = function () {
alert('button clicked');
};
$scope.make = null;
$scope.$watch('make', function () {
alert('how do I tell when the make has been changed?');
this.$parent.$parent.filterModels(make.id);
});
});
HTML
<div>
<div class="col-md-12" style="margin-bottom: 3px">
<div class="col-md-4 col-md-offset-1" style="padding-top: 6px; padding-left: 0px"><label>Equipment</label></div>
<div class="col-md-offset-10">
<button class="btn btn-primary btn-sm" ng-click="addEquipment()">Add row</button>
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<table class="table table-bordered table-hover table-condensed">
<tr style="font-weight: bold; background-color: lightblue">
<td style="width:35%">Name</td>
<td style="width:20%">Make</td>
<td style="width:20%">Model</td>
<td style="width:25%">Edit</td>
</tr>
<tr ng-repeat="equip in equipment" ng-controller="editRowController">
<td>
<!-- editable equip name (text with validation) -->
<span editable-text="equip.name" e-name="name" e-form="rowform" onbeforesave="checkName($data, equip.id)" e-required>
{{ equip.name || 'empty' }}
</span>
</td>
<td>
<!-- editable make (select-local) -->
<span editable-select="equip.make" e-name="make" e-form="rowform" e-ng-options="s.value as s.name for s in makes">
{{ showMake(equip) }}
</span>
</td>
<td>
<!-- editable model (select-remote) -->
<span editable-select="equip.model" e-name="model" e-form="rowform" e-ng-options="g.id as g.name for g in models" onbeforesave="checkModel($data, equip.id)" e-required>
{{ showModel(equip) }}
</span>
<button type="button" ng-disabled="rowform.$waiting" ng-click="testClick()" class="btn btn-default">
test
</button>
</td>
<td style="white-space: nowrap">
<!-- form -->
<form editable-form name="rowform" onbeforesave="saveEquipment($data, equip.id)" ng-show="rowform.$visible" class="form-buttons form-inline" shown="inserted == equip">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-primary">
save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button class="btn btn-primary" ng-click="rowform.$show()">edit</button>
<button class="btn btn-danger" ng-click="removeEquipment($index)">del</button>
</div>
</td>
</tr>
</table>
</div>
</div>
ng-repeat creates a child scope for each row (for each equipment). The scope of the EditRowController is therefore a childScope of the parent quoteBuckingRaterController.
This childScope contains:
all properties of the parent scope (e.g. equipment, makes, models)
the property equip with one value of the equipment array, provided by ng-repeat
any additional scope property that is defined inside the ng-repeat block, e.g. rowform
Therefore you are able to access these properties in the childController editRowController using the $scope variable, e.g.:
$scope.equip.make
$scope.equipment
and inside the ng-repeat element in the html file by using an angular expression, e.g:
{{equip.make}}
{{equipment}}
Now to $scope.$watch: If you provide a string as the first argument, this is an angular expression like in the html file, just without surrounding brackets {{}}. Example for equip.make:
$scope.$watch('equip.make', function (value) {
console.log('equip.make value (on save): ' + value);
});
However, angular-xeditable updates the value of equip.make only when the user saves the row. If you want to watch the user input live, you have to use the $data property in the rowform object, provided by angular-xeditable:
$scope.$watch('rowform.$data.make', function (value) {
console.log('equip.make value (live): ' + value);
}, true);
You can also use ng-change:
<span editable-select="equip.make" e-name="make" e-ng-change="onMakeValueChange($data)" e-form="rowform" e-ng-options="s.value as s.name for s in makes">
JS:
$scope.onMakeValueChange = function(newValue) {
console.log('equip.make value onChange: ' + newValue);
}
That should solve your first question: How to watch the make property.
Your second question, how to detect when the row is editable and when it is not, can be solved by using the onshow / onhide attributes on the form or by watching the $visible property of the rowform object in the scope as documented in the angular-xeditable reference
<form editable-form name="rowform" onshow="setEditable(true)" onhide="setEditable(false)">
$scope.setEditable = function(value) {
console.log('is editable? ' + value);
};
// or
$scope.$watch('rowform.$visible', function(value) {
console.log('is editable? ' + value);
});
You might ask why the rowform object is in the current childScope.
It is created by the <form> tag. See the Angular Reference about the built-in form directive:
Directive that instantiates FormController.
If the name attribute is specified, the form controller is published
onto the current scope under this name.
A working snippet with your example code:
angular.module('app', ["xeditable"]);
angular.module('app').controller("editRowController", function ($scope) {
$scope.testClick = function () {
alert('button clicked');
};
$scope.$watch('equip.make', function (value) {
console.log('equip.make value (after save): ' + value);
});
$scope.$watch('rowform.$data.make', function (value) {
console.log('equip.make value (live): ' + value);
}, true);
// detect if row is editable by using onshow / onhide on form element
$scope.setEditable = function(value) {
console.log('is equip id ' + $scope.equip.id + ' editable? [using onshow / onhide] ' + value);
};
// detect if row is editable by using a watcher on the form property $visible
$scope.$watch('rowform.$visible', function(value) {
console.log('is equip id ' + $scope.equip.id + ' editable [by watching form property]? ' + value);
});
});
angular.module('app').controller("quoteBuckingRaterController", function ($scope, $filter) {
$scope.equipment = [];
$scope.makes = [{value: 1, name: 'Horst'}, {value: 2, name: 'Fritz'}];
$scope.models = [{id: 1, name: 'PC', make: 1}];
$scope.showModel = function(equip) {
if(equip.model) {
var selected = $filter('filter')($scope.models, {id: equip.model});
return selected.length ? selected[0].name : 'Not set';
} else {
return 'Not set';
}
};
$scope.showMake = function(equip) {
if (equip.model) {
var selected = $filter('filter')($scope.models, { id: equip.model });
if (selected.length && selected.length > 0) {
if (equip.make != selected[0].make)
equip.make = selected[0].make;
return selected[0].make;
}
else {
return 'Not set';
}
} else {
return 'Not set';
}
};
$scope.checkName = function (data, id) {
if (!data) {
return "Description is required";
}
};
$scope.checkModel = function (data, id) {
if (!data) {
return "Model is required";
}
};
$scope.saveEquipment = function (data, id) {
$scope.inserted = null;
};
$scope.cancelRowEdit = function (data, id) {
$scope.inserted = null;
};
$scope.removeEquipment = function(index) {
$scope.equipment.splice(index, 1);
};
$scope.addEquipment = function() {
$scope.inserted = {
id: $scope.equipment.length+1,
name: '',
make: null,
model: null
};
$scope.equipment.push($scope.inserted);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-xeditable/0.1.9/js/xeditable.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angular-xeditable/0.1.9/css/xeditable.css" rel="stylesheet"/>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div ng-app="app" ng-controller="quoteBuckingRaterController">
<div class="col-md-12" style="margin-bottom: 3px">
<div class="col-md-4 col-md-offset-1" style="padding-top: 6px; padding-left: 0px"><label>Equipment</label></div>
<div class="col-md-offset-10">
<button class="btn btn-primary btn-sm" ng-click="addEquipment()">Add row</button>
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<table class="table table-bordered table-hover table-condensed">
<tr style="font-weight: bold; background-color: lightblue">
<td style="width:35%">Name</td>
<td style="width:20%">Make</td>
<td style="width:20%">Model</td>
<td style="width:25%">Edit</td>
</tr>
<tr ng-repeat="equip in equipment" ng-controller="editRowController">
<td>
<!-- editable equip name (text with validation) -->
<span editable-text="equip.name" e-name="name" e-form="rowform" onbeforesave="checkName($data, equip.id)" e-required>
{{ equip.name || 'empty' }}
</span>
</td>
<td>
<!-- editable make (select-local) -->
<span editable-select="equip.make" e-name="make" e-form="rowform" e-ng-options="s.value as s.name for s in makes">
{{ showMake(equip) }}
</span>
</td>
<td>
<!-- editable model (select-remote) -->
<span editable-select="equip.model" e-name="model" e-form="rowform" e-ng-options="g.id as g.name for g in models" onbeforesave="checkModel($data, equip.id)" e-required>
{{ showModel(equip) }}
</span>
<button type="button" ng-disabled="rowform.$waiting" ng-click="testClick()" class="btn btn-default">
test
</button>
</td>
<td style="white-space: nowrap">
<!-- form -->
<form editable-form name="rowform" onbeforesave="saveEquipment($data, equip.id)" ng-show="rowform.$visible" class="form-buttons form-inline" shown="inserted == equip" onshow="setEditable(true)" onhide="setEditable(false)">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-primary">
save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button class="btn btn-primary" ng-click="rowform.$show()">edit</button>
<button class="btn btn-danger" ng-click="removeEquipment($index)">del</button>
</div>
</td>
</tr>
</table>
</div>
</div>
If you simply want to $watch the make property of equipment, try changing to:
$scope.$watch('equipment.make', function(){(...)})
You could write your own directive for this.
The main advantage is that directives have isolated scope and can have their own controller.
see the directive documentation to know if it's for you.

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