Remove unchecked value from an array angular js - javascript

I am new to angular js. I have a checkbox with a table .
<td><input type="checkbox" ng-if="report.attributes.message.length > 0" ng-bind="report.attributes.message" ng-click="getcheckedData(report.attributes.message)">{{ report.attributes.message }}</td>
Here , I have a method getcheckedData(). So, In that method
var messages = [];
$scope.getcheckedData = function(SelectedVal) {
$("input:checkbox[type=checkbox]:checked").each(function() {
if ($.inArray(SelectedVal , messages) === -1){
messages.push(SelectedVal);
}
});
return messages;
};
I have an array which I declared globally,.So, I want to take the value of selected checkbox table data into that array. I am able to get that value in array. So, when user unchecks then the value which is unchecked should also get removed from that array . So, when user checks then ,
I have given one button on that I am sending all checked messages to the backend.
So, When I uncheck and press the button that time all messages still remain in the array.
$scope.sendAllMessages = function() {
uploadService.SendMessagesToQueue(uploadService.currentFileName,$scope.documentType,messages)
.then(function () {
}, function (error) {
$scope.errorMessage = error.status + " : " + error.statusText;
toastr.error($scope.errorMessage, 'Error : ' + error.status);
if (error.status === 401) {
loginService.authenticationError();
}
})
.finally(function () {
});
};
For button -
<button type="submit" ng-click = "sendAllMessages()" class="button-size btn btn-primary">Send </button>
so, How can I resolve this problem ?

What you have done is not the angular way of achieving what you need.
But if you need to do in the same way of Yours, here is the change you should do.
You should remove the value from the array if it is unchecked, using messages.splice(index, 1);
Here is the changed code of your's, without ng-model(not recommended)
var messages = [];
$scope.getcheckedData = function(SelectedVal) {
if ($.inArray(SelectedVal , messages) === -1){
messages.push(SelectedVal);
}
else
{
var index = messages.indexOf(SelectedVal)
messages.splice(index, 1);
}
return messages;
};
To achieve it in angular way, you need to use ng-model
Here is a sample using Angular
var app = angular.module('app', []);
function Ctrl($scope) {
$scope.messages = {
};
$scope.reports = [ { "name": "Sport", "id": "50d5ad" } , {"name": "General", "id": "678ffr" } ];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="Ctrl" ng-app="app">
<span ng-repeat="report in reports">
<label class="checkbox" for="{{report.id}}">
<input type="checkbox" ng-model="messages[report.id]" name="group" id="{{report.id}}" />
{{report.name}}
</label>
</span>
<pre ng-bind="messages | json"></pre>
</div>

Related

How I can trigger a function with a button click which is already set to be triggered with "Enter" Key press in AngularJS?

So I was trying to make it possible to add a product to the cart by a button click beside the ENTER key press(which is now the only way to add a product to the cart), I have tried many times but unfortunately all ways does not work at all.
This is a POS system project built with AngularJS (which my experience in it, is very weak) And I need to make it badly
here is the HTML part:
<tr>
<td colspan="6" class="text-center">
<input autofocus autocomplete="off" list="product-list"
id="product-entry" type="text" class="form-control"
name="product-reference" required/><br/>
<button id="myButton" ng-click="" >Add Product to Sale</button>
<datalist id="product-list">
<option ng-repeat="item in inventory" value="{{ item.name }}">
</option>
</datalist>
</td>
</tr>
I need to make it when someone click "myButton" ,I imagine that I need to add some function in ng-click directive,But Any other ways are welcomed
And Here is the JS part :
// POS Section
pos.controller('posController', function ($scope, $routeParams, Inventory, Transactions) {
$scope.barcode = '';
function barcodeHandler (e) {
$scope.barcodeNotFoundError = false;
$scope.barcode = $('#product-entry').val();
var regex=/^[0-9]+$/;
// if enter is pressed
if (e.which === 13) {
if(!$scope.barcode.match(regex)){
for(var i = 0; i < $scope.inventory.length; i++) {
if($scope.inventory[i].name === $scope.barcode) {
$scope.barcode = $scope.inventory[i].barcode;
break;
}
}
}
if ($scope.isValidProduct($scope.barcode)) {
$scope.addProductToCart($scope.barcode);
$scope.barcode = '';
$scope.productsList = '';
$scope.$digest();
$('#product-entry').val($scope.barcode);
}
else {
window.alert('product not found: ' + $scope.barcode);
console.log('invalid product: ' + $scope.barcode);
// $scope.barcodeNotFoundError = true;
}
}
}
$('#product-entry').off('keypress').on('keypress', barcodeHandler);
What you're doing is listening for a keyup event on the field, and if that key matches the return key, it continues with your logic.
If you move the logic into its own function (before barcodeHandler), you can access it elsewhere:
$scope.doSomething = function() {
$scope.barcodeNotFoundError = false;
$scope.barcode = $('#product-entry').val();
var regex=/^[0-9]+$/;
if(!$scope.barcode.match(regex)){
for(var i = 0; i < $scope.inventory.length; i++) {
if($scope.inventory[i].name === $scope.barcode) {
$scope.barcode = $scope.inventory[i].barcode;
break;
}
}
}
if ($scope.isValidProduct($scope.barcode)) {
$scope.addProductToCart($scope.barcode);
$scope.barcode = '';
$scope.productsList = '';
$('#product-entry').val($scope.barcode);
}
else {
window.alert('product not found: ' + $scope.barcode);
console.log('invalid product: ' + $scope.barcode);
// $scope.barcodeNotFoundError = true;
}
};
Then inside barcodeHandler, use:
if (e.which === 13) {
$scope.doSomething();
}
Now in your markup, You can do:
<button id="myButton" ng-click="doSomething()">Add Product to Sale</button>
Adding something to the $scope of the controller is a way of making it available in the view.

Store multiple checkbox inputs in local storage

I have multiple checkbox inputs that look like this:
<input type="checkbox" id="box-1">
<input type="checkbox" id="box-2">
<input type="checkbox" id="box-3">
I want to store their values (checked or unchecked) in the browser's local store.
The javascript that I'm using to do this is:
function onClickBox() {
let checked = $("#box-1").is(":checked");
let checked = $("#box-2").is(":checked");
let checked = $("#box-3").is(":checked");
localStorage.setItem("checked", checked);
}
function onReady() {
let checked = "true" == localStorage.getItem("checked");
$("#box-1").prop('checked', checked);
$("#box-2").prop('checked', checked);
$("#box-3").prop('checked', checked);
$("#box-1").click(onClickBox);
$("#box-2").click(onClickBox);
$("#box-3").click(onClickBox);
}
$(document).ready(onReady);
The first part saves the checkbox's state on the click and the second part loads it when the page refreshes.
This works well if the lines for box 2 and 3 are removed, but I need it to work with all the checkboxes.
Your main issue here is that you're only storing a single value in localStorage, checked, which will be overwritten every time you check a different box. You instead need to store the state of all boxes. An array is ideal for this, however localStorage can only hold strings, so you will need to serialise/deserialise the data when you attempt to read or save it.
You can also simplify the logic which retrieves the values of the boxes by putting a common class on them and using map() to build the aforementioned array. Try this:
<input type="checkbox" id="box-1" class="box" />
<input type="checkbox" id="box-2" class="box" />
<input type="checkbox" id="box-3" class="box" />
jQuery($ => {
var arr = JSON.parse(localStorage.getItem('checked')) || [];
arr.forEach((c, i) => $('.box').eq(i).prop('checked', c));
$(".box").click(() => {
var arr = $('.box').map((i, el) => el.checked).get();
localStorage.setItem("checked", JSON.stringify(arr));
});
});
Working example
function onClickBox() {
let checked1 = $("#box-1").is(":checked");
let checked2 = $("#box-2").is(":checked");
let checked3 = $("#box-3").is(":checked");
localStorage.setItem("checked1", checked1);
localStorage.setItem("checked2", checked2);
localStorage.setItem("checked3", checked3);
}
function onReady() {
let checked1 = "true" == localStorage.getItem("checked1");
let checked2 = "true" == localStorage.getItem("checked2");
let checked3 = "true" == localStorage.getItem("checked3");
$("#box-1").prop('checked', checked1);
$("#box-2").prop('checked', checked2);
$("#box-3").prop('checked', checked3);
$("#box-1").click(onClickBox);
$("#box-2").click(onClickBox);
$("#box-3").click(onClickBox);
}
$(document).ready(onReady);
Of course you could simplify it further by doing
function onClickBox(boxNumber) {
let checked = $("#box-" + boxNumber).is(":checked");
localStorage.setItem("checked" + boxNumber, checked);
}
function onReady() {
[1, 2, 3].forEach( function(boxNumber) {
$("#box-" + boxNumber).prop(
'checked',
localStorage.getItem("checked" + boxNumber)
);
$("#box-" + boxNumber).click( function() {
localStorage.setItem(
"checked" + boxNumber,
$("#box-" + boxNumber).is(":checked")
);
});
})
}
$(document).ready(onReady);
Your check variable is getting overwritten, you can put it inside for loop.
So your code becomes,
function onClickBox() {
for(var i=1;i<=3;i++){
let checked=$("#box-"+i).is(":checked");
localStorage.setItem("checked-"+i, checked);
}
}
function onReady() {
for(var i=1;i<=3;i++){
if(localStorage.getItem("checked-"+i)=="true"){
var checked=true;
}
else{
var checked=false;
}
$("#box-"+i).prop('checked', checked);
onClickBox();
}
}
$(document).ready(onReady);
Please follow the below Code (Very Simple Javascript works)
<input type="checkbox" id="box">checkbox</input>
<button type="button" onClick="save()">save</button>
<script>
function save() {
var checkbox = document.getElementById("box");
localStorage.setItem("box", checkbox.checked);
}
//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked;
</script>
with simple modification, you can use it without save button..
Hope this Helps you..

Angular filter with list of items in an array

I have an array of objects with user and interests. I would like to filter the list based on interests. An user can have multiple interests and when selected interests check boxes the list should filter out based on those interests. I've used a basic filter on ng-repeat but it's not working.
If I select "sports" then "John" and "Rosaline" should be shown.
If I select "movies" and "reading" then all 3 users should be shown.
Below is my code.
Plunker: https://plnkr.co/edit/A0ojO3MH8rDhFJVXlEAs?p=preview
View:
<div ng-app="myApp" ng-controller="myController" style="padding:20px">
<input type="checkbox" ng-model="selection.reading" ng-true-value="'reading'" ng-false-value="''">reading
<input type="checkbox" ng-model="selection.sports" ng-true-value="'sports'" ng-false-value="''">sports
<input type="checkbox" ng-model="selection.movies" ng-true-value="'movies'" ng-false-value="''">movies
<br><br>
Selected Values: {{selectedValues}}
<hr>
<div ng-repeat="d in data | filter: selectedValues">
<h4>
Name: {{d.user}}
</h4>
<h4>
Interests: {{d.interests}}
</h4>
<hr>
</div>
Controller:
$scope.selection = {};
$scope.data = [
{
user: "John",
interests: ["reading","sports","movies"]
},
{
user: "David",
interests: ["movies","reading"]
},
{
user: "Rosaline",
interests: ["sports","movies"]
}
];
$scope.$watchCollection('selection', function () {
$scope.selectedValues = [];
angular.forEach($scope.selection, function (value, key) {
if (value) {
$scope.selectedValues.push(value);
}
});
});
Here is one of many ways to filter objects in such examples.
I suggest getting rid of using $watch in this situation and implement checkboxes functionality via simple ngChange directive. Example below.
<input type="checkbox" ng-model="selection.reading" ng-change="selectInterest('reading')">reading
<input type="checkbox" ng-model="selection.sports" ng-change="selectInterest('sports')">sports
<input type="checkbox" ng-model="selection.movies" ng-change="selectInterest('movies')">movies
$scope.selectInterest = function(interest){
$scope.selection[interest] = !!$scope.selection[interest];
};
For filtering data I recommend using $filter or (just to simplify example) implement this filter like a controller function.
$scope.filterUsers = function(user){
return Object.keys($scope.selection).some(function (item) {
return user.interests.indexOf(item) >= 0 && $scope.selection[item];
});
};
You can look at and play with the whole code of my example at the link above.
Modify your html a bit in ng-repeat
<div ng-repeat="d in data" ng-hide="selectedValues.length > 0 && !filteredData(d.interests)">
<h4>
Name: {{d.user}}
</h4>
<h4>
Interests: {{d.interests}}
</h4>
<hr>
</div>
And add this function in script.js
$scope.filteredData = function (data) {
var found = false;
for (var i = 0; i < $scope.selectedValues.length; i++) {
if (data.indexOf($scope.selectedValues[i]) !== -1) { found = true; break; }
}
return found;
};
Live example :
https://plnkr.co/edit/y8tqNiIU6p3x8d9zcdzL?p=preview
This will work ! Thanks
Your can keep your filters in some array e.g. filterInterests and then your HTML could looks like:
<div ng-repeat="d in data">
<div ng-show="hasInterest(d.interests, filterInterests)">
// Your code here
</div>
</div>
And your function will looks like:
function hasInterest(data, interests){
var result = false;
// Iterate over interests from filter and check them all in provided data
for(var=i, i<interests.length, i++){
if(data.indexOf(i) != -1) result = true
else result = false;
}
return result;
}

Angular to disable ng-repeat checkbox based on value

I have a list of checkbox displayed using ng-repeat, now i need to disable some checkbox based on specific value checkbox is checked.
checkbox display code
<div class="checkbox">
<label ng-repeat="specific in specifications">
<input ng-click="onClick(specific, newObject[specific])" id="specifications_chk" value="{{specific}}" ng-model="newObject[specific]" type="checkbox">
{{specific}}
</label>
</div>
Here am using ng-click function to disable checkbox.
This is my controller code:
$scope.onClick = function(sp, checked){
if(sp == 'Sofa_Cleaning' && checked === true){
angular.element(document.getElementById('specifications_chk'))[0].disabled = true;
}
if(sp == 'Sofa_Cleaning' && checked === false){
angular.element(document.getElementById('specifications_chk'))[0].disabled = false;
}
};
html view:
in controller code am able disable only first value (IndepthHomeCleaning), so how can i disable Room_Cleaning, Kitchen_Cleaning, and Carpet_cleaning when Sofa_Cleaning is checked
Am i stuck with this, Help will be really appreciated
I don't know why you are still stick with the jquery. You are getting
by id when you are trying to disable the checkbox.
.
In html, id should be unique for the current html page. y ou are
having duplicated ids and you are getting the first value from the
array using [o] when you are trying to disable.
.
If you strictly want solution from the same method then use the
following methodology Use class name instead of id for the check boxes and use
angular element and disable.
The following code should be used where you need to disable. Use appropriate code based on your need.
angular.forEach(document.getElementsByClassName('checkbox1'), function(value, key) {
angular.element(value)[0].disabled = true;
debugger
});
If you want to change specifications array you need a new array and mapping.
Define new row object for each specification.
Access specification row and its prop (is active or is disable) from your specification.
http://jsfiddle.net/ms403Ly8/87/
function testCtrl($scope, $filter) {
$scope.specifications = ["IndepthHomeCleaning", "Room_Cleaning", "Kitchen_Cleaning", "Carpet_cleaning", "Sofa_Cleaning"];
$scope.specificationRows = [];
$scope.newRow = function(spec) {
var newSpec = {
SpecName: spec,
IsDisabled: false,
IsClicked: false
};
$scope.specificationRows.push(newSpec);
};
$scope.getRowObject = function(sp) {
return $filter('filter')($scope.specificationRows, {
SpecName: sp
})[0];
};
$scope.getRowStatus = function(spec) {
console.log($filter('filter')($scope.specificationRows, {
SpecName: spec
})[0].IsDisabled);
return $scope.getRowObject(spec).IsDisabled;
};
$scope.onClick = function(sp) {
$scope.getRowObject(sp).IsClicked = !$scope.getRowObject(sp).IsClicked;
if (sp == 'Sofa_Cleaning') {
$scope.getRowObject("Carpet_cleaning").IsDisabled = $scope.getRowObject(sp).IsClicked;
$scope.getRowObject("Kitchen_Cleaning").IsDisabled = $scope.getRowObject(sp).IsClicked;
$scope.getRowObject("Room_Cleaning").IsDisabled = $scope.getRowObject(sp).IsClicked;
}
};
}
getRowObject is example. Maybe it's not best practice. You can change this function.
You should not have same id for multiple elements in your code. You need to make you elements ids unique.
HTML :
<div ng-app ng-controller="LoginController">
<div class="checkbox">
<label ng-repeat="specific in specifications">
<input id="specifications_chk{{$index}}" ng-click="onClick(specific, newObject[specific])" value="{{specific}}" ng-model="newObject[specific]" type="checkbox" /> {{specific}}
<br>
</label>
</div>
</div>
JavaScript :
function LoginController($scope) {
$scope.specifications = ['IndepthHomeCleaning',
'Room_Cleaning',
'Kitchen_Cleaning',
'BathroomCleaning',
'Carpet_cleaning',
'Sofa_Cleaning'
];
$scope.newObject = {
'IndepthHomeCleaning': 1,
'Room_Cleaning': 2,
'Kitchen_Cleaning': 3,
'BathroomCleaning': 4,
'Carpet_cleaning': 5,
'Sofa_Cleaning': 6
};
$scope.onClick = function(sp, checked) {
if (sp == 'Sofa_Cleaning' && checked === true) {
angular.element(document.getElementById('specifications_chk1'))[0].disabled = true;
angular.element(document.getElementById('specifications_chk2'))[0].disabled = true;
angular.element(document.getElementById('specifications_chk4'))[0].disabled = true;
}
if (sp == 'Sofa_Cleaning' && checked === false) {
angular.element(document.getElementById('specifications_chk1'))[0].disabled = false;
angular.element(document.getElementById('specifications_chk2'))[0].disabled = false;
angular.element(document.getElementById('specifications_chk3'))[0].disabled = false;
}
};
}
JsFiddle : https://jsfiddle.net/nikdtu/f7k3kcwn/
use ng-disabled
var angApp = angular.module('myApp', []);
angApp.controller('MyController', function MyController($scope) {
$scope.specifications = [{"text":"IndepthHomeCleaning ", "disabled":false, "checked":false},
{"text":"Room_Cleaning", "disabled":false, "checked":false},
{"text":"Kitchen_Cleaning", "disabled":false, "checked":false},
{"text":"BathroomCleaning", "disabled":false, "checked":false},
{"text":"Carpet_cleaning", "disabled":false, "checked":false},
{"text":"Sofa_Cleaning", "disabled":false, "checked":false}];
$scope.onClick = function(sp, checked){
console.log(sp, checked);
if(sp.text == 'Sofa_Cleaning' && checked){
$scope.specifications[1].disabled = true;
$scope.specifications[2].disabled = true;
$scope.specifications[4].disabled = true;
}
if(sp.text == 'Sofa_Cleaning' && !checked){
$scope.specifications[1].disabled = false;
$scope.specifications[2].disabled = false;
$scope.specifications[4].disabled = false;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<div class="checkbox">
<label ng-repeat="specific in specifications" style="display:block">
<input ng-disabled="specific.disabled" ng-change="onClick(specific, specific.checked)" id="specifications_chk" value="specific.checked}" ng-model="specific.checked" type="checkbox">
{{specific.text}}
</label>
</div>
</div>
I think you're over complicating this. Your data object should be simplified to look like this
$scope.specifications = [
{name: 'Sofa_Cleaning', active: false},
{name: 'Carpet_Cleaning', active: false},
{name: 'Room_Cleaning', active: false},
{name: 'Kitchen_Cleaning', active: false},
{name: 'BathroomCleaning', active: false}
];
Template:
<input type="checkbox"
ng-bind="specific.name"
ng-model="specific.active"
ng-disabled="shouldDisable(specific)">
in your controller
$scope.disableWhenSofaIsChecked = ['Room_Cleaning','Kitchen_Cleaning','Carpet_Cleaning'];
$scope.shouldDisable = function(specific) {
var disable = $scope.disableWhenSofaIsChecked;
if(disable.indexOf(specific.name) > -1) {
for(var obj in $scope.specifications) {
if(obj.name === 'Sofa_Cleaning') {
return obj.active;
}
}
}
return false;
}
EDIT
So if you're getting specifications data from API, you can just do this:
SomeApi
.get()
.then(function(results){
// Assuming it's a promise. End result is the same for a passed-in callback
// Assuming results is an array of names
$scope.specifications = results.map(function(item){
return {
name: item,
active: false
};
});
});
You are using 'id' attribute which should be unique for each DOM element. So definitely your solution will take single element. So you should try using class attribute and document.getElementbyClass function.
Don't use jquery to for dom manipulation.
Use ng-change instead of ng-click. This will be the appropriate one.
Here I've update a plunkr.
Here for the simple example, I've done like
if the value is check5 then disable all the checkboxes. Otherwise enable the checkboxes.
https://jsfiddle.net/AvGKj/517/
Note: I've used little bit old plugin. Please take the logics alone
<div ng-controller="MyCtrl">
<table>
<tr ng-repeat="appObj in myAppObjects">
<td>
<input type="checkbox" ng-model="appObj.cb1"
ng-disabled="appObj.disable"
ng-change="Disable(appObj,myAppObjects)">
{{appObj.value}}
</td>
</tr>
</table>
{{myAppObjects}}
<br>list of checked items: {{checkedItems()}}
</div>
function MyCtrl($scope) {
$scope.myAppObjects = [
{id:1,value:'check1'},
{id:2,value:'check2'},
{id:3,value:'check3'},
{id:4,value:'check4'},
{id:5,value:'check5'}
];
$scope.Disable=function(appObj,list)
{
if(appObj.value=="check5")
{
for(var i=0; i<list.length;i++)
{
if(list[i].value!="check5")
{
if(appObj.cb1==true)
{
list[i].disable=true;
}
else{
list[i].disable=false;
}
}
}
}
}
}

delete dynamically added values to the ng-repeat(angularjs)

First of all, happy thanksgiving to everyone of you !!
I have this plunker-> http://plnkr.co/edit/N2bs5xqmtsj3MmZKEI25?p=info
User selects all the three values and only then the 'Add' button is enabled for addition.
Once clicked, the entries selected are shown below using ng-repeat. I also a delete button button to every row which gets added. How can i ensure that the delete functionality works in this case. ? i.e. if i click delete, only that particular row will be deleted.
Secondly, if u have noticed during the first add, a single delete button is shown above the first row. how can i remove that?
I also want to save the selected files in the controller so i can give those data to the backend. How can i know which options have been selected by user.
here is the plunker code-
HTML
<div ng-controller="Controller">
<form name="form" novalidate>
<input type='file' onchange="angular.element(this).scope().fileNameChanged(this)" ng-model="document" valid-file required>
<select name="singleSelect" ng-model="activeItem.content" ng-options="foo as foo for foo in contentarray" required>
<option ng-if="contentarray.length > 1" value="" selected>Choose</option>
</select>
<select name="singleSelect1" ng-model="activeItem.content1" ng-options="foo as foo for foo in content1array" required>
<option ng-if="content1array.length > 1" value="" selected>Choose</option>
</select>
<button ng-click="addItem()" ng-disabled="disableAdd || (form.$invalid && (!form.$valid && 'invalid' || 'valid'))">Add</button>
</form>
<div ng-repeat="item in items" ng-show="isvisible">
<a>{{item.name}}</a>
<a>{{item.content}}</a>
<a>{{item.content1}}</a>
<button ng-click="deleteItem()">Delete</button>
</div>
</div>
JS code
var app = angular.module('Select', []);
app.controller('Controller', function($scope, $timeout) {
/* for adding optional file based selection values selected by the user*/
$scope.isvisible = false; /* display 1st line when user clicks on add button*/
$scope.items = [{
}];
$scope.activeItem = {
name: '',
content: '',
content1: ''
}
$scope.fileNameChanged = function (el) {
$scope.activeItem.name = el.files[0].name
}
$scope.addItem = function () {
$scope.isvisible = true;
$scope.items.push($scope.activeItem);
if ($scope.items.length > 6) {
$scope.disableAdd = true
}
$scope.activeItem = {} /* reset active item*/
angular.element("input[type='file']").val(null); /* To clear the input type file selected for next selection*/
}
/* for showing select options and enabling add button only when both the options are selected*/
$scope.content = {};
$scope.content1 = {};
$scope.contentarray = ['2', '3'];
$scope.content1array = ['12', '121', '1233', '1211'];
$scope.trigger = function () {
$timeout(function () {
$('form.bad select').trigger('change');
})
}
});
I am referring to your deleteItem() and delete-button-problem:
You will have to implement your deleteItem() method in your controller. ng-repeat will automatically update your list, when you delete an item from the model ìtems, no need for angular.element. This works, because of two-way data-binding in Angular.
Add an id to your ìtems and use that to delete the item from the model e.g.:
$scope.addItem = function() {
//...
$scope.activeItem.id = $scope.items.length;
$scope.items.push($scope.activeItem);
//...
}
$scope.deleteItem = function(item) {
$scope.items.splice(item.id, 1);
}
In your ng-repeat you need to define your button like this:
<button ng-click="deleteItem(item)">Delete</button>
Your other problem is with the additional delete-button: That is displayed, because you initialize your model ìtems with an empty element. Initialize like this instead and the button will not be shown:
$scope.items = [];
Hope that helps

Categories

Resources