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

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.

Related

Dom7 - getJson works but unable to transfer data

I'm working on top of Urban Dictionary api example of Framework7.
This is the resulting JSON from the url (edit don't ask me why but it starts with an 'a'):
a{
"bills": [
{
"id": 8,
"name_id": "6",
"category_id": 4,
"isPaid": "Yes",
"value": "190.00",
"expiry": "2016-12-15 00:00:00",
"created_at": "2017-01-04 15:44:00",
"updated_at": "2017-01-04 15:44:00",
"name": {
"id": 6,
"name": "Test1",
"created_at": "2017-01-04 15:39:45",
"updated_at": "2017-01-04 15:39:45"
},
"category": {
"id": 4,
"name": "System",
"created_at": "2017-01-04 15:37:43",
"updated_at": "2017-01-04 15:37:43"
}
}
]
}
This is the piece of code on my-app.js:
function getrandom() {
// Get JSON Data from UrbanDictionary API
$$.getJSON('http://[privateurl]', function (json) {
// Insert rendered template
$$('#content-wrap').html(compiledTemplate(json));
});
};
I try to get the results by doing: console.log(getrandom());
I get: Undefined
It doesn't load my list.
{{#each list}}
<li>
<a href="{{bill_id}}" class="item-link item-content external" target="_blank">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">"{{bill_id}}"</div>
<div class="item-text">by {{value}}</div>
</div>
</div>
</a>
</li>
{{/each}}
However, if I do this: console.log($$.getJSON('http://hiddenapiurl'));
I get results just fine.
edit: The actual urban dictionary api works normally. But mine doesn't for some reason.
EDIT2
Below is the whole code for my-app.js:
var myApp = new Framework7({});
var $$ = Dom7;
// Select Template
var template = $$('#random-template').html();
// Compile and render
var compiledTemplate = Template7.compile(template);
// Defined as function "getrandom"
function getrandom() {
$$.getJSON('http://[privateurl]', function (json) {
// Insert rendered template
console.log(json);
$$('#content-wrap').html(compiledTemplate(json));
});
};
console.log($$.getJSON('http://[privateurl]'));
getrandom();
// Select Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content');
// On refresh
ptrContent.on('refresh', function (e) {
// Emulate 1s loading
setTimeout(function () {
// Execute getrandom to get new Definitions
getrandom();
myApp.pullToRefreshDone();
}, 1000);
});
var mainView = myApp.addView('.view-main', {
dynamicNavbar: true
});
First, getrandom() function does not have a return, that's why console.log(getrandom()) says Undefined!
Second, where did you select the template that you are compiling with compiledTemplate?
For example:
var searchTemplate = $('#list-template').html();
var compiledSearchTemplate = Template7.compile(searchTemplate);
myApp.onPageInit('search', function (page) {
// Just execute compiled search template with required content:
var html = compiledSearchTemplate({/*...some data...*/});
// Do something with html...
});
Please double check the Framework7 example.
EDIT 2:
Why are you saying each list while your json array name is bills?
Try using each bills or each this.bills.
And the a that is bothering you because your json file has an a letter at the beginning of it!
Good luck man!

Angularjs Load "$ scope" in a table based on a select

I try to view the "$ scope" in the table to be displayed according to the select chosen. Keeping the default selection in the select.
The $scope that are in the json just a server. example : " status " : $ scope.DC01_GF1_STATUS "
Here is modeled : https://plnkr.co/edit/CaWNeIDHe2nFyEgDABvg?p=preview
$scope.templates = {"webapp": {
"Dc01": [
{
"name": "Groupe Froid 1A",
"value": "gf1a",
"data": {
"status": $scope.DC01_GF1_STATUS,
"capacite": $scope.DC01_GF1_CAP_T
},
},
{
"name": "Groupe Froid 3A",
"value": "gf3a",
"data": {
"status": $scope.DC01_GF3_STATUS,
"capacite": $scope.DC01_GF3_CAP_T
},
}]
}
};
Thank you
You are missing some data. You'll need to import it.
Here's an example: https://plnkr.co/edit/NPfRM0
relevant code:
// loading dummy status codes:
$scope.DC01_GF1_STATUS = 'status GF1'
$scope.DC02_GF1_STATUS = 'status GF2'
$scope.DC01_GF1_CAP_T = 10
$scope.DC02_GF1_CAP_T = 5
...
$scope.testBat = function(arg) {
...
$scope.capacite = $scope.templates.webapp[arg][0].data.capacite;
$scope.status = $scope.templates.webapp[arg][0].data.status;
...
}
index.html change
<p class="gfInterface">{{capacite}} %</p>
the problem comes from the declaration of the "$scope". The problem comes when I select a title in the "select" for example "Groupe Froid 3A" values "$scope" name, capacite and status does not change. Because the $scope of such name is $scope.name = $scope.templates.webapp[building][0].name; but for the selection "Groupe Froid 3A" the $scope should be $scope.name = $scope.templates.webapp[building][1].name;. And it is like for the rest. I would have come to retrieve the id or the value of intitullé selected to generate the $scope.name example. As for building variable $scope.templates.webapp[building][number].name. The variable retrieves the id of the selection.

Delete item using ANgularJS

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.

Proper display of layered json data

I have json that looks like this:
[
{
"Id": 1,
"Name": "Item1",
"Order": 1,
"Categories": [
{
"Id": 1,
"Name": "Item1-Subitem1",
"Order": 1,
"Subcategories": [
{
"Id": 1,
"Name": "Item1-Subitem1-Subsubitem1",
"Order": 2
},
{
"Id": 2,
"Name": "Item1-Subitem1-Subsubitem2",
"Order": 1
},
...
and with angular I need to display on first page (or route) link on main items. For example:Item1Item2And when clicked on them links should be displayed with names from 'Categories'For example:Item1-Subitem1Item1-Subitem2And when clicked on these links there should be displayed links with name from 'Subcategories'For example:Item1-Subitem1-Subsubitem1Item1-Subitem1-Subsubitem2
Now my first links work but I don't know how to get that nested data from same json according to value from url. When I click on links in first view I go to page I need but without data. No errors is displayed. I belive I need to parse id from url but how to achieve that?
It can be checked here http://plnkr.co/edit/GTfLFQepFcXzXYcIHnP0I am using ui-router
In secondList.js, you've defined your scope with the wrong name. It should be:
scope: {
secondList: '='
},
After you fix that, you're also missing the final factory in service.js:
app.factory('singleList', ['$http', function ($http) {
return {
get: function () {
return $http.get('data.json').then(function (re) {
return re.data;
});
}
};
}])

angularjs - select with object of object as options

I'm currently trying to build a AngularJS app with a complex data structure.
The data source is an array of people with languages and skill level.
I need to filter those people by language skill, to do so I tried to build a select with the languages and another select with the skill levels, but i failed.
Here is a plnkr of my effords
Maybe there is also a simpler/better way to structure the data array ($scope.people)
Take a look at this
Working Demo
Html
<div ng-app='myApp' ng-controller="MainCtrl">LANGUAGES:
<select ng-model="selectLang" ng-options="lang as lang for lang in languages"></select>
<br>SKILL:
<select ng-model="selectSkill" ng-options="skill as skill for skill in skills"></select>
<br>
<button ng-click="getPeople()">Submit</button>
<br>PEOPLE:
<select ng-model="selectPeoples" ng-options="people as people for people in peoples"></select>
</div>
script
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.people = [{
"name": "Jane Doe",
"gender": "Female",
"languages": [{
"lang": "German",
"skill": "Good"
}, {
"lang": "English",
"skill": "Very Good"
}]
}, {
"name": "John Doe",
"gender": "Male",
"languages": [{
"lang": "French",
"skill": "Good"
}, {
"lang": "English",
"skill": "Very Good"
}]
}];
$scope.languages = [];
$scope.skills = [];
angular.forEach($scope.people, function (peopleValue, peopleKey) {
angular.forEach(peopleValue.languages, function (langValue, langKey) {
$scope.languages.push(langValue.lang);
$scope.skills.push(langValue.skill);
});
});
$scope.languages = _.uniq($scope.languages);
$scope.skills = _.uniq($scope.skills);
$scope.getPeople = function () {
$scope.peoples = [];
angular.forEach($scope.people, function (peopleValue, peopleKey) {
angular.forEach(peopleValue.languages, function (langValue, langKey) {
if (langValue.lang === $scope.selectLang && langValue.skill === $scope.selectSkill) {
$scope.peoples.push(peopleValue.name);
}
});
});
}
});
Your problem is that you're not actually looping through each person's languages array in your ng-options directive. And I don't believe such a thing is actually possible given how your data is structured. I don't think you can loop through nested arrays (or at least I'm not aware of any ng-options syntax that would allow for such a thing.
So to make things easier, I would suggest doing the following in your controller:
$scope.langs = [];
angular.forEach($scope.people, function(person){
angular.forEach(person.languages, function(lang){
$scope.langs.push({
lang: lang.lang,
skill: lang.skill,
name: person.name,
gender: person.gender
});
});
});
This will give you an array that will allow you to filter using ng-options with the `orderBy' filter.

Categories