Removing selected row from an array using splice in angularjs - javascript

I have an issue in removing the particular item from an array.I have tried using splice but, the last row is removing instead of the particular row.I am providing the plunker link here :
$scope.rows.splice($index, 1);
https://plnkr.co/edit/WETSLqOXlTwiHq4p9IUt?p=preview
Any help would be appreciated . Thanks

just try the following
http://jsfiddle.net/oymo9g2f/2/
you have some problem with your array splice

Not quite sure what you're trying to accomplish (as your code looks like you are quite new to AngularJS, but I created a different (but similar) implementation that should fit your needs (it's easier to read IMHO and is scalable):
HTML:
<div class="card ">
<form name="add_destination_form" class="col s12" ng-submit="add_destination_form.$valid && addDestination_Details(destination_details)" novalidate>
<div class="row" ng-repeat="row in rows track by $index">
<div class="col s12 m4" >
<label for="destination_features1" >Features</label>
<textarea id="destination_features1" name="destination_features1_{{$index}}" ng-model="destination_details.destination_features1[$index]" placeholder="Data Here" type="text" ></textarea>
</div>
<button ng-show="show_removebtn" id="removeButton" ng-click="removeDynamically($index)" type="button">Remove</button>
</div>
<div class="col s12 m4">
<button class="waves-effect waves-light btn" ng-click="addDynamically()" type="button">Add More</button>
</div>
<div class="row">
<div class="col s12 m4">
<button type="submit">Submit</button>
</div>
</div>
</form>
</div>
JavaScript:
$scope.rows = [{
"row_num": 0,
"text": ""
}];
$scope.addDynamically = function (index) {
console.log(index);
$scope.rows.push({
"row_num": index,
"text": ""
});
};
$scope.removeDynamically = function (index) {
$scope.rows.splice(index, 1);
};
Plunker

just use this code. For text area used ng-model="row.value" and related change in controller
in html: just shown ng-repeat part
<div class="row" ng-repeat="row in rows track by $index">
<div class="col s12 m4" >
<label for="destination_features1" >Features</label>
<textarea id="destination_features1" name="destination_features1_{{$index}}" ng-model="row.value" placeholder="Data Here" type="text" ></textarea>
</div>
<button ng-show="show_removebtn" id="removeButton" ng-click="removeDynamically($index)" type="button">Remove</button>
</div>
and in controller:
$scope.rows = [];
$scope.current_rows = 0;
$scope.destination_details = {};
$scope.rows.push({
row_num: $scope.current_rows,
value: ''
});
$scope.addDynamically = function() {
$scope.current_rows += 1;
$scope.rows.push({
row_num: $scope.current_rows,
value: ''
});
if ($scope.rows.length > 1) {
$scope.show_removebtn = true;
}
};
$scope.removeDynamically = function(index) {
if (index > -1) {
$scope.rows.splice(index, 1);
}
};

You need to add line:
$scope.destination_details = {"destination_features1": ['1']};
at the beginning.
Also need to remove model properly when removing element:
$scope.destination_details.destination_features1.splice($index, 1);
https://plnkr.co/edit/pe44Moqe7ymegYFTrXJu?p=preview

Related

Showing changes without refreshing in VueJS

I'm so new in VueJS and still don't control much of its funcionalities,
I'm trying when I update or delete something in my window not need to refresh to see the changes...how can I do it, please?
My functions work perfectly in my controller, just need to solve the question of seeing changes.
Here I post my code if it helps...thank you very much!!
UpdateProfile.vue:
<div class="field">
<label class="label">Schedules</label>
<!--Edit and Delete Schedules-->
<div v-for="schedule in sortedDays(data.schedulesDisplayed)" class="control">
<div class="container">
<div class="field">
<label class="label">Week Day: {{schedule.week_day}}</label>
</div>
<div class="row">
<div class="col">
<div class="row">
Opening Time: <input class="input" type="text" placeholder="Pub schedules" v-model="schedule.opening_time">
</div>
</div>
<div class="col">
<div class="row">
Closing Time: <input class="input" type="text" placeholder="Pub schedules" v-model="schedule.closing_time">
</div>
</div>
</div>
<div class="field">
<div class="buttons is-left">
<div class="button is-info" #click="updatePubSchedule(schedule)">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Save</span>
</div>
<div class="button is-danger" #click="deletePubSchedule(schedule)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete Schedule</span>
</div>
</div>
</div>
</div>
</div>
</div>
updatePubSchedule(schedule){
var instance = this;
this.api.put('/pubschedules/update/' + this.data.id, schedule).then(response => {
console.log(schedule);
//data = response.data;
instance = response.data;
});
},
deletePubSchedule(schedule){
var instance = this;
this.api.delete('/pubschedules/delete/' + this.data.id, schedule).then(response => {
//data = response.data;
instance = response.data;
});
},
And in my controller:
/**
* #param Pub $pub
*/
public function updatePubSchedule(Pub $pub)
{
//json_die(request()->all());
Schedule::where([
['pub_id','=', $pub->id],
['week_day' ,'=', request()->get('week_day')]
])->update(request()->all());
}
/**
* #param Pub $pub
*/
public function deletePubSchedule(Pub $pub)
{
Schedule::where([
['pub_id','=', $pub->id],
['week_day' ,'=', request()->get('week_day')]
])->delete();
}
I don't know how you get your initial data but you can have a GET request that gets fresh data from the laravel after you update/delete initial data.
With the response from that request you can update your data.schedulesDisplayed prop.
Important! You need to set the :key attribute in the div that uses v-for rendering like this
<div v-for="(schedule, index) in sortedDays(data.schedulesDisplayed)" :key="index" class="control">
I used the index for the sake of this example but you should use a unique property of sortedDays return.

Creating a JSON Object in views and passing it in HTML

views.py - Django 2.0.2
def hotels(request):
list_of_hotels = Hotel.objects.order_by('hotel_name')
template = loader.get_template('myapp/hotels.html')
data = {}
for each in list_of_hotels:
data[str(each.hotel_name)] = 'null'
json_data = json.dumps(data)
context = {
'list_of_hotels': list_of_hotels,
'json_data': json_data,
}
return HttpResponse(template.render(context, request))
hotels.html
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">search</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label for="autocomplete-input">Search</label>
</div>
</div>
</div>
</div>
<script>
var jsonObj = "{{json_data}}";
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: jsonObj,
});
});
</script>
I'm trying to parse a JSON Object from Django views into a script located inside the corresponding HTML page. I tried everything, but it just doesn't seem to work. I searched Stack Overflow for about an hour now, and based on all the answers came to these snippets of code, which still don't work. Any leads on how to go about it would be highly appreciated!
P.S: In the script in hotels.html, the data takes in a JSON Object. For more details on the initialisation, refer to this.
P.P.S: I am an absolute noob in JavaScript/ jQuery.
Found a solution to my own problem after a lot of tries. Thanks to anyone who tried to help me. :)
hotels.html
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">search</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label for="autocomplete-input">Search</label>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
var jsonObj = {{ json_data|safe }};
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: jsonObj,
});
});
</script>
views.py
def hotels(request):
list_of_hotels = Hotel.objects.order_by('hotel_name')
template = loader.get_template('myapp/hotels.html')
data = {}
for each in list_of_hotels:
data[str(each.hotel_name)] = None
json_data = json.dumps(data)
context = {
'list_of_hotels': list_of_hotels,
'json_data': json_data,
}
return HttpResponse(template.render(context, request))

I can´t remove the last item of array

I can remove any item of array unless the last one. I also use angularjs to show information in the view. I don´t know what is happening with the last item of this array. Please, anyone can help me?
Here is HTML:
<div class="row">
<div class="col-md-12">
<h4><strong>Documento {{index + 1}} de {{documentos.length}}:</strong> {{documentos[index].nome}}</h4>
<iframe style="background: #ccc;" ng-show="exibirPreview" frameborder="0" ng-src="{{versaoLink}}" width="100%" height="300px"></iframe>
<div class="alert alert-warning" ng-hide="exibirPreview">
#Html.Raw(Resources.Dialog.SignDocuments.TypeDocumentCanNotPreDisplayed)
</div>
<hr />
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<button class="btn btn-default" type="button" ng-click="RemoveDoc(index)"><i class="fa fa-fw fa-times"></i> #Resources.Common.RemoveDocList</button>
</div>
</div>
</div>
Here is js/angularjs
$scope.documentos = [
{nome:"document1", chave: "8F65579E3737706F", extensao:".pdf"},
{nome:"document2", chave: "8F65579E3730007F", extensao:".pdf"},
{nome:"document3", chave: "8545579E3737706F", extensao:".pdf"},
{nome:"document4", chave: "8555579E3730007F", extensao:".pdf"}
]
$scope.ViewLink = function () {
var versao = $scope.documentos[$scope.index];
$scope.exibirPreview = versao.extensao == ".pdf" || versao.extensao == ".txt";
if (!$scope.exibirPreview) {
$scope.versaoLink = '';
} else {
$scope.versaoLink = '/Documento/VersaoView?chave=' + versao.chave;
}
};
$scope.ViewLink();
$scope.RemoveDoc = function (index) {
$scope.documentos.splice(index, 1);
$scope.ViewLink();
};
Or Plunker
In your HTML you are preventing the deletion of the last element:
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<!-- -->
</div>
documentos.length > 1 means "hide when it reaches one item in the array".
It should be documentos.length == 0.
It's either this or your index value starts from 1 and not from 0.
The simplest solution would be to change your remove function to take in the document instead of the index. Try this:
$scope.RemoveDoc = function(document) {
var index = $scope.documents.indexOf(document);
$scope.documents.splice(index, 1);
}
in view:
<button class="btn" type="button" ng-click="RemoveDoc(document)">Delete</button>

how to delete object in an array with filter used? AngularJS

I have something like an input to add items into either column 1 or column 2 and each time adding the items, the column will show up what is added right away with an 'X' beside it so if you want to delete the item just click on 'X'. At first I wasn't thinking much so I used an easy way to remove the HTML but then I realized, that's just removing the HTML (There's also a search input if I type something into search and clear the search, all items will show again). This is when I realized just removing the HTML is a mistake that I need to remove the object too but how can I make it so it'll delete the right object in the array?
My angular script
angular.module("addItemApp", [])
.controller("toDoCtrl", function ($scope) {
$scope.items = [];
$scope.addItem = function (item) {
console.log(item);
$scope.items.push(angular.copy(item));
console.log($scope.items);
};
$scope.remove = function (item) {
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
}
});
my html
<div class="row">
<div class="col-xs-6 col-sm-4 left-column">
<div class="input-item">
<input type="text" placeholder="Enter Item" ng-model="item.name" class="enter-item">
<select class="column-select" ng-model="item.pos">
<option value="default" selected>Choose Column</option>
<option value="column1">Column 1</option>
<option value="column2">Column 2</option>
</select>
<button class="add-button" type="button" ng-click="addItem(item)">Add Item</button>
</div>
<div class="search-item">
<label for="search">Search An Item</label>
<div class="search-input">
<input ng-model="query" type="text" placeholder="Search" id="search"><span class="fa fa-search icon-search"></span>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4">
<h3 class="column-header column1">
Column 1
</h3>
<ul ng-repeat="item in items | filter:{ pos: 'column1' } | filter:query">
<li>{{item.name}}
<button remove-on-click ng-click="remove()" class="remove-button fa fa-times"></button>
</li>
</ul>
</div>
<!-- Optional: clear the XS cols if their content doesn't match in height -->
<div class="clearfix visible-xs-block"></div>
<div class="col-xs-6 col-sm-4">
<h3 class="column-header column2">
Column 2
</h3>
<ul ng-repeat="item in items | filter:{ pos: 'column2' } | filter:query">
<li>{{item.name}}
<button remove-on-click ng-click="remove()" class="remove-button fa fa-times"></button>
</li>
</ul>
</div>
</div>
Thanks in advance everyone.
you can do it in two ways -
1
$scope.remove = function(item) {
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
}
<button ng-click="remove(item)"></button>
2
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
<button ng-click="remove($index)"></button>
Please note that, when filter is applied, the $index may not be the one you should use to remove, better go with first approach. I have given example of $index for your reference.
<button ng-click="remove(item)"></button>
should work, since item is defined earlier in the ng-repeat and you already have a remove function defined on your $scope.

Is JQuery breaking my functionality?

I am making an app, the user can either select an item or use their camera to get the qr code which translates into an item's ID.
The problem is that I think some JQuery is messing with my scope from working properly.
I have to get the QR code by listening to an innerHtml change, once it changes (DOMSubtreeModified) the following occurs.
var index = 0;
$('#result').one('DOMSubtreeModified', function(e) {
var code = "";
if (e.target.innerHTML.length > 0) {
code = e.target.innerHTML;
$scope.ToRun(code);
}
});
$scope.ToRun = function(code) {
for (i = 0; i < $scope.plantList.length; i++) {
if ($scope.plantList[i].plantcode == code) {
index = i;
break;
}
}
$scope.currentPlant = $scope.plantList[index];
$scope.plantDetails = false;
$scope.searchDetails = true;
}
For some reason the following does not have any effect on my ng-classes. As when an item is selected I hide the input dialogs, and show the result one.
$scope.plantDetails = false;
$scope.searchDetails = true;
But when a user selects the item manually it works just perfectly. (the items have an ng-click on it)
$scope.viewPlant = function(plant) {
$scope.currentPlant = plant
$scope.plantDetails = false;
$scope.searchDetails = true;
};
And the above works fine, with the ng-click. So why won't my new function that listens for an innerHtml change work?
HTML snippet
<div ng-class="{ 'hidden': searchDetails }">
<!-- CHOOSE INPUT TYPE -->
<div class="form-group" style="margin-bottom:0px">
<div class="btn-group btn-group-justified">
<div class="btn-group">
<button type="button" class="btn btn-default" ng-click="digits = false; qr = true">Plant Code</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-default" ng-click="digits = true; qr = false">QR Code</button>
</div>
</div>
</div>
<br />
<!-- QR CODE INPUT -->
<div ng-class="{ 'hidden': qr }">
<img id="blah" src="./images/placeholder.png" />
<span class="btn btn-default btn-file">
<i class="glyphicon glyphicon-camera"></i>
<input type="file" onchange="readURL(this);handleFiles(this.files)">
</span>
<div id="result">xxxxxx</div>
<canvas id="qr-canvas" width="800" height="600"></canvas>
</div>
<!-- MANUAL SELECTION INPUT -->
<div ng-class="{ 'hidden': digits }">
<input ng-model="search.$" style="width:100%; font-size:30px; text-align:center" placeholder="Plant Code" />
<div style="overflow: auto; max-height:250px">
<table class="table table-striped" style="background-color:lightblue">
<tr ng-repeat="plant in plantList | filter:search" ng-click="viewPlant(plant)" style="cursor:pointer">
<th>{{plant.name}}</th>
<th>{{plant.plantcode}}</th>
</tr>
</table>
</div>
</div>
<div>
</div>
</div>
<div ng-class="{ 'hidden': plantDetails }">
// results - this should appear when one of the above is entered.
// works for manual selection, but not qr code
</div>
Just confused on why my QR input will not fire off the change-class options to hide the searchDetails div and show the plantDetails div
EDIT: Doing a small test, it seems that my class variables are indeed not updating at all. I just put the values at the bottom of my page and they do not update when hitting the block of:
$scope.plantDetails = false;
$scope.searchDetails = true;
You need to let Angular know about the change. Add this at the end of your method and let me know if it works.
$scope.$apply();

Categories

Resources