Delete item using ANgularJS - javascript

I have a JSON file which contains data. I can print the data using ANgularJS. It will show in row with a checkbox and there is a Delete button. I want to delete the data from display and as well as from JSON file. Delete process would be like, Click on the checkbox which you want to Delete > Click on the Delete button. This is my plnkr link :-
http://plnkr.co/edit/A07XJk1RQNmhSnLFqLxH?p=preview
api.json is the JSON file.
This is the JSON file look like :-
{
"1": {
"venture": "XYZ Informatics",
"member": [
{
"name": "abcd",
"email": "abcd#gmail.com"
}
],
"message": "This is good day",
"isclicked": false
},
"2": {
"venture": "BBC Informatics",
"member": [
{
"name": "xyz",
"email": "xyz#gmail.com"
}
],
"message": "This is bad day",
"isclicked": true
}
}

Add ng-model to checkbox....then iterate data and use delete if it is checked
$scope.delete = function() {
angular.forEach($scope.datas, function(val, key) {
if (val.isclicked) {
delete $scope.datas[key];
}
})
}
View
<form ng-repeat="data in datas">
<input type="checkbox" ng-model="data.isclicked">{{ data.venture }}
</form>
<button ng-click="delete()">Delete</button>
DEMO

Assuming you have your data is on the scope, you'd use the JavaScript delete function to remove an item from the array.
So...
delete $scope.data["1"]
Angular's digest should update anything watching that scope property automatically.

Related

Create dynamic form with parameters

On a grid I have to create a (popup) form dynamically, based on a JSON that has the data for what type of input goes on the form.
For the select type, the options are different for every form, and all the options are in another JSON that is called based on the name on the previous JSON.
example.
I click on button "create report" for row number 1 on grid. popup open up with form to get the filter of the report. the button call the 1st JSON that is like this:
[
{
"name": "Report Users residence",
"input": [{
"type": "select",
"name": "city",
},
{
"type": "select",
"name": "address",
}]
}
]
In this case the cities are in another JSON called "city.json".
[
{
"code": "000000",
"description": "City1"
},
{
"code": "000001",
"description": "City2",
}
]
I was able to create the form, but i don't know how to get the option of the 2nd JSON on the select "city".Can someone give me an example on how to do it?
First, city data have to converted into object. After that using jQuery $.each method, you can loop over city object to create option for select and append into the select.
This is an example of the idea :
<select name="city"></select>
<script>
var city = [{"code":"000000","description":"City1"},{"code":"000001","description":"City2",}];
var citySelect = $(document).find('select[name="city"]');
$(city).each(function(key,item){
var cityOption = new Option(item.description,item.code);
citySelect.append(cityOption);
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="city"></select>
<script>
var city = [{"code":"000000","description":"City1"},{"code":"000001","description":"City2",}];
var citySelect = $(document).find('select[name="city"]');
$(city).each(function(key,item){
var cityOption = new Option(item.description,item.code);
citySelect.append(cityOption);
});
</script>

Allow for conditional .filter() and .map() in AngularJS on-change?

I have a problem where I am unable to edit the actual script of the page. That means I cannot add an AngularJS filter, directive, and so on. I am pretty limited, so I can only edit the HTML.
I want to be able to, based on the input from a dropdown, filter an existing list based on the selected property. This is relatively easy, and it can be done like this:
myArray.filter(x => x.Type == selectedType)
However, AngularJS throws up an error, because it won't allow me to use either .filter(function(){}) or .filter(x => x). At first I thought it was a problem with lambda, since AngularJS might not support that, but it turns out it's basically impossible to filter an array based on its properties.
This is my initial object:
[{
"id": "random",
"type": "1",
"name": "First tag"
},
{
"id": "random-2",
"type": "1",
"name": "Second tag"
},
{
"id": "random-3",
"type": "2",
"name": "Third tag"
}]
and if I do .filter(x => x.type = "2"), I should be able to get this list back:
[{
"id": "random-3",
"type": "2",
"name": "Third tag"
}]
Take a lookt at this Plunker: https://embed.plnkr.co/yudKIhsB2OQ9Phh0X1am
The "Filtered tags" in the HTML should show the filtered tags based on this condition (which works in normal JavaScript-language):
ng-change="vm.FilteredTags = vm.Tags.filter(x => x.type == vm.SelectedValue)"
You can filter out type property value which is matching vm.SelectedValue.
<p>Filtered tags: {{vm.Tags | filter: {type: vm.SelectedValue}: true }}</p>
Or using alias it would be way simpler, no need to have it on ng-change.
<div ng-repeat="vm.Tags | filter: {type: vm.SelectedValue}: true as FilteredTags">
... your sutff here...
<div>

Drop-down empty selection from the menu

I work with a JavaScript app and populate the drop-down menu with a JSON list.
$("#address").append($('<option></option>').attr("value", "1").text(""));
$.each(wallets, function (index, wallet) {
if (selectedCurrency === wallet["currency"].toString().trim()) {
$("#address").append($('<option></option>').attr("value", "1").text(wallet["address"]));
}
})
The UI looks like this,
If I select the empty item (like in the picture), I would like to print empty in the console. Otherwise, I want to print the address value. My intention is to write more code, but, this is where I would like to get started. The code I have,
$("#address").change(function () {
if($(this).val()===""){
console.log('empty');
}
else{
console.log($(this).val());
}
}
However, it only prints 1 in the console and can't distinguish between the empty bar and the address in concern. If I use console.log("The value is " + $(this).text()); inside the change function, it prints every info all together in the console,
The value is mp51mPC38Wtcmybdyd9MPEB2bKnw6eYbCsmqXjM7Mmg6B5LWMad7mHJi339ddaj7xXdBmvXxP1GmXXKojWQJKjgeoASnXVNXCS47z6n41jE2BKKpV6LsPb7dDdStjtuJf1FrYvMMmw1jtrWU5DADxvNR421MKFW1fposgzVMBymnzcZVF4jtZtGAggM5GuLog3Y5o52Mx4xMmq5Rgggfgy2TiRsvtcGm3rxx12R8XbYi9omkdt7ouyJnDXUp4LzdRSRP3ZhU57gUDKy6n2F2QEKk6Fqqk2yMTope5MYp1RtpT949kemrkdfp6qoVN3YiyJhq6nXPvgr3f7YpkS9j
The JSON data I have is something like,
[
{
"id": 1,
"code": "BTC",
"address": "mp51mPC38Wtcmybdyd9MPEB2bKnw6eYbCs",
"currency": "Bitcoin"
},
{
"id": 2,
"code": "BTC",
"address": "mqXjM7Mmg6B5LWMad7mHJi339ddaj7xXdB",
"currency": "Bitcoin"
},
{
"id": 4,
"code": "BTC",
"address": "mvXxP1GmXXKojWQJKjgeoASnXVNXCS47z6",
"currency": "Bitcoin"
}
// some more data
]
What the issue here? My guess is I do something wrong to append the data to the drop-down list and needs to be changed.
I can provide more info if required ....
Just change the value 1 to "" in first option.
$("#address").append($('<option></option>').attr("value", "").text(""));
$.each(wallets, function (index, wallet) {
if (selectedCurrency === wallet["currency"].toString().trim()) {
$("#address").append($('<option></option>').attr("value", "1").text(wallet["address"]));
}
});
check this example.
$("#address").append($('<option></option>').attr("value", "").text(""));
$("#address").append($('<option></option>').attr("value", "1").text("123"));
$("#address").append($('<option></option>').attr("value", "2").text("456"));
$("#address").change(function () {
if($(this).val()===""){
console.log('empty');
}
else{
console.log($(this).val());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="address">
</select>

Javascript/Jquery push json objects into array

I have an json object coming from a $.post in jquery.
In order to loop through and store the data clientside I would like to add it to an array. For each search results that comes back I would like to "append" the array so it grows.
This is my json:
{
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
} ]
}
This is what I have come up with so far were data is the json
comming back fron the post ajax request. Obj is just an object holding the array
which I declared further up in my code. obj.companies = new Array();
obj.companies.push(data['companies']);
The next part I need to loop out the array. Trying to do it like this.
$.each(obj.companies, function(i, item) {
// Does not alert correctly.
alert(item.header);
});
So I need to push the full json object into the array. But I cannot alert the item.header within the loop, how can I accomplish this?
EDIT:
Thanks everyone. Sorry if my question wasnt detailed enough.
I ended up doing this:
getcompanies: function() {
obj = this;
$.post('api/finder/result.php', {}, function(data) {
$.each(data.companies, function(i, item) {
obj.companies.push(item);
});
obj.loadcompanies();
}, "json");
},
loadcompanies: function() {
$.each(this.companies, function(i, item) {
alert(item.header);
}
}
I believe there is a issue with your server side code which is responsible for building JSON object which is getting returned via Ajax. The Correct JSON should be as follows:
{
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
}
]
}
Please note that there is only single key with name "companies" which holds an array of objects. Please correct your server side code to get such valid JSON. You can use free online JSON validator tools such as http://jsonlint.com/ to validate your JSON objects.
Now once you get such response from server; you just need to do following steps to get the companies array (following code will go into $.post success handler):
var jsonResp = JSON.parse(postResponse); //postResponse is the success resp of $.post
var companiesArray = jsonResp.companies;
$.each(companiesArray , function (index, valueObj){
var compId = valueObj.companyid;
var isSaved = valueObj.saved;
});
I hope this will help you a bit.
if you want to append new company into your companies array you should
var json_obj = {
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
} ]
};
//adding new company into your companies array
json_obj.companies.push({
"companyid":"117",
"saved" : false,
"orgnumber": "20120313",
"companyname":"anotherCompany",
"header":"another header info"
});
//if you want to loop through your companies list you can:
json_obj.companies.map(function ( obj ){
console.log(obj.companyid);
console.log(obj.companyname);
etc..
});

How to write array which collects ng-click event in AngularJs?

I am working with a project, where I need to collect multiple items from user and send it to the server. There is list on my view, where user can click and select the items. My HTML looks like this,
HTML
<div ng-repeat="topicList in searchCtrl.topic">
<div ng-repeat="topicTerm in topicList">
<p>{{topicTerm.number}}&nbsp&nbsp{{topicTerm.name}}</p>
<div ng-repeat="subTopic in topicTerm.subTopics">
{{subTopic.number}}&nbsp&nbsp{{subTopic.name}}
</div>
</div>
</div>
I have used anchor tag, there user can click and at the same time I want the clicked items (which have also unique ID) collected in an Array or variable, which I need to send (these selected items) to the server via form submission.
This is how my controller looks like,
JavaScript Controller
angular.module('myApp').controller("searchController", function($log, searchService, $scope){
var self = this;
self.initializeSearch = function(){
self.searchEntry =
{
"contact":{
"person": "",
"organization": ""
},
"request": {
"input": "",
"language": "en"
},
"topicIds": []
};
// The POST request must looks like above
What I want is that the clicked subTopics IDs collects in an Array "topicIds : []" and I could successfully send the POST request mentioned above. The searchService is a Angular service which helps to get Topics from server and also to POST user input to the server.
This is how my JSON looks like,
JSON API
{
"TopicList" :[
{
"id": "798790fa-78c8-4f00-8179-9e70f40adb14",
"name": "Topic1",
"number": 1.0,
"subTopics": [
{
"id": "82c90f2e-deac-4fa4-80f4-d077edacc2dc",
"name": "data1.1",
"number": 1.1
},
{
"id": "0f0c2b89-6dae-4f60-90f8-df49d96b9af9",
"name": "data1.2",
"number": 1.2
},
{
"id": "131b68b6-1f45-477f-9b0f-8ac80c5b4f4e",
"name": "data1.3",
"number": 1.3
},
{
"id": "16c8f46d-d20c-48f9-a0c0-e3989763082b",
"name": "data1.4",
"number": 1.4
}
]
},
{
"id": "9ed3fee0-5347-4f00-9b56-721b61439f88",
"name": "Topic2",
"number": 2.0,
"subTopics": [
{
"id": "eec13511-1408-4f4b-be6f-8b5a8b6ea28b",
"name": "data2.1",
"number": 2.1
},
...
]
},
...
]
}
How to write a function or array which collects the IDs via ng-click event?
Thanks in Advance.
No need to use an $event, simple pass the subTopic.id, or whatever, in your ng-click, like ng-click="searchCtrl.select(subTopic)"
And then in your controller, you could have:
angular.module('myApp').controller("searchController", function($log, searchService, $scope){
var self = this;
var subTopicIds = []; // array to hold subTopicIds
self.select = function(subTopic) {
subTopicIds.push(subTopic.id);
}
self.initializeSearch = function(){
self.searchEntry =
{
"contact":{
"person": "",
"organization": ""
},
"request": {
"input": "",
"language": "en"
},
"topicIds": subTopicIds // use the object created previously
};
...
You can get an ID in angular like this.
<div ng-click="recordClick($event)">Click</div>
That will feed the click event into the recordClick method, where you can then call it's target property (i.e. the div it was invoked on) and push it in the array.
$scope.clickArray = [];
$scope.recordClick = function(event){
clickArray.push(event.target);
}
I solved this problem by passing subTopics ID in ng-click as a parameter. And as per the requirement I need to call also another event while user click, which I passed as a second argument. So, now both the events works as I wanted via single ng-click.
Here is my updated code,
HTML
<div ng-repeat="topicList in searchCtrl.topic">
<div ng-repeat="topicTerm in topicList">
<p>{{topicTerm.number}}&nbsp&nbsp{{topicTerm.name}}</p>
<div ng-repeat="subTopic in topicTerm.subTopics">
{{subTopic.number}}&nbsp&nbsp{{subTopic.name}}
</div>
</div>
</div>
And here is my controller,
Controller
angular.module('myApp').controller("searchController", function($log, searchService, $scope){
var self = this;
var subTopicIDs = [];
self.select = function(TopicIDs, event){
subTopicIDs.push(TopicIDs);
$(event.target).addClass('selor'); // This is class which changes the background color of the clicked item
console.log(TopicIDs);
}
self.initializeSearch = function(){
self.searchEntry =
{
"contact":{
"person": "",
"organization": ""
},
"request": {
"input": "",
"language": "en"
},
"topicIds": subTopicIDs
};
This is how it solved my problem.
Btw, Thank you Tom and OceansOnPluto.

Categories