I have the following piece of code...
var mainArray =
{
nestedArrays:
{
array1:[... items ...],
array2:[... items ...]
}
};
var source =
'{{#nestedArrays}}' +
'{{#each this}}' +
'<div class="listItem" onclick="populateSecondMenu({{SEND THIS ARRAY!}});">' +
'<div class="leftSide">' +
'<div class="listTitle">Indicator : {{this.length}} </div>' +
'</div>' +
'</div>' +
'{{/each}}' +
'{{/items}}';
var template = Handlebars.compile(source);
$('.list').html(template(mainArray));
As you can already see here, I am able to iterate over this structure, and place the length of both "array1" and "array2" inside list items on the UI.
However, What I also want to be able to do - is to be able to pass the current item to a the function when inside the "#each" tags - see that function call, "populateSecondMenu"? I want to put the array I am at now - so that I can pass that in, How might I do that?
Thanks in advance!
try this. I have used arguments
<script type="text/javascript">
function populateSecondMenu(item) {
console.log(arguments);
}
</script>
<div class="entry">
<h1></h1>
<div class="body">
{{#nestedArrays}}
{{#each this}}
<div class="listItem" onclick="populateSecondMenu({{this}})">
<div class="leftSide">
<div class="listTitle">Indicator : {{this.length}} </div>
</div>
</div>
{{/each}}
{{/nestedArrays}}
</div>
</div>
Related
I have an event form that where I get information put it in the localstorage (I cannot use an API) and I want to take the startdate and enddate out of localstorage, change them so they appear as dd-mm-yyyy (not yyyy-mm-ddT00:00:00.000Z) The issue is getting them out of the array and setting them. I have no idea where to begin....
Here is my JavaScript/jQuery:
.controller("Events", function($scope, $location) {
let URL = "https://morning-castle-91468.herokuapp.com/";
$scope.authToken = localStorage.getItem("authToken");
$scope.username = localStorage.getItem("username");
$scope.events = [];
let lastEvent = 0;
while (localStorage.getItem("event"+lastEvent)){
$scope.events.unshift(JSON.parse(localStorage.getItem("event"+lastEvent)));
lastEvent++;
}
JSON.parse(localStorage.getItem("event")) || [];
$scope.submitForm = function() {
if ($scope.eventForm.$valid) {
$scope.event.username = $scope.username;
localStorage.setItem("event"+lastEvent, JSON.stringify($scope.event));
}
};
})
And here is my HTML:
<div class="row eventcontent" ng-repeat="event in events">
<div class="col-xs-12 eventpost">
<div class="row-flex">
<div class="col-xs-8 ">
<h4>{{ event.title }}</h4>
</div>
<div class="col-xs-4 ">
<h4>{{ event.name }}</h4>
</div>
<div class="col-xs-12 ">
<td>{{ event.description }}</td>
<br />
<br />
<p>{{ event.address }} <br /> {{ event.country }}</p>
<br />
<p>{{ event.status }}</p>
</div>
<div class="col-xs-12 ">
<p>{{ event.startdate }} {{ event.enddate }}</p>
</div>
</div>
</div>
</div>
To get Data from localstroage which will be an JSON ArrayList then,
var retrievedData = JSON.parse(localStorage.getItem("event"+lastEvent));
var setDateFormat = $filter('date')(new Date((retrievedData[1].substr(6)), 'dd-mm-yyyy'));
I'm not used to Angular.
But anyway, it looks like you are creating an array events having all the previously stored event.
You use unshift which is adding each event at the beginning of the array. The result probably is like so (for 2 elements):
$scope.events:
[ // That is event1
{
name:someValue,
description:someValue,
address:someValue,
country:someValue,
status:someValue,
startdate:"yyyy-mm-ddT00:00:00.000Z",
enddate:"yyyy-mm-ddT00:00:00.000Z"
},
// That is event0
{
//Same structure as above...
}
]
So now,, assuming you wish to have the last event, which is the first element in the events array, and the structure is as above, I would try:
// Retreive the dates from the first array element... Only the part before the "T" in each string.
var retreived_start = $scope.events[0].startdate.split("T")[0];
var retreived_end = $scope.events[0].enddate.split("T")[0];
// Split the date by the "-" to re-order...
var start_parts = retreived_start.split("-");
var end_parts = retreived_start.split("-");
// YYYY-MM-DD results
var formatted_start = start_parts[2] +"-"+ start_parts[1] +"-"+ start_parts[0];
var formatted_end = end_parts[2] +"-"+ end_parts[1] +"-"+ end_parts[0];
// Place it in your Angular controller array (? -- I'm unsure here)
$scope.event.startdate = formatted_start;
$scope.event.enddate = formatted_end;
But now that you've modified the event array... It may be stored as "formatted"... So be aware of that!
That line is doing absolutely nothing: JSON.parse(localStorage.getItem("event")) || [];, since not assigned to a variable, you can safely remove it.
I'm writing a user settings page in Angular that will be used to update the users profile settings. This is how I've done it (pardon my use of jquery please)
$scope.userObj = {};
var userObjTemp = {};
$http.get('/api/to/get/user').success(function(data) {
if (data.success != true) {
$state.go('index');
} else {
$scope.userObj.user = data.response; //scope variable to show in html form
userObjTemp.user = data.response; //temp data in case someone cancels editing
var tempDob = $scope.userObj.user.dob;
$scope.userObj.user.dob = tempDob.split('-')[2] + '/' + tempDob.split('-')[1] + '/' + tempDob.split('-')[0];
console.log({
userObjData: $scope.userObj
});
console.log({
tempData: userObjTemp
});
}
});
$scope.showSetting = function(target) {
$('.setting-edit-row').hide();
$('.jr-input-setting').show();
$('#' + target + '-input').hide();
$('#' + target).show();
}
$scope.saveSetting = function(key) {
var postDict = {};
postDict[key] = $scope.userObj.user[key];
$http.put('/api/user', postDict).success(function(data) {
$scope.userObj.user = data.response;
$('.setting-edit-row').hide();
$('.jr-input-setting').show();
})
}
$scope.shutSetting = function(target) {
$scope.userObj.user = {};
$scope.userObj.user = userObjTemp.user;
$('#' + target).hide();
$('#' + target + '-input').show();
}
My HTML is as follows:
<div class="row setting-fixed-row">
<div class="col-lg-2">
<div class="setting-label">
Name
</div>
</div>
<div class="col-lg-8">
<input class="jr-input-setting" id="setting-name-input" disabled="true" ng-model="userObj.user.display_name" type="text" placeholder="Display Name">
</div>
<div class="col-lg-2">
<div class="edit-btn" ng-click="showSetting('setting-name')">
Edit
</div>
</div>
<div class="col-lg-12 setting-edit-row" id="setting-name">
<div class="row">
<div class="col-lg-12">
<span class="glyphicon glyphicon-remove shut-det" style="margin-bottom: 5px;" ng-click="shutSetting('setting-name')"></span>
</div>
<div class="col-lg-offset-2 col-lg-8">
<input class="jr-input-edit" ng-model="userObj.user.display_name" placeholder="Display Name" id="display_name" ng-change="showVal()">
</div>
<div class="col-lg-2">
<div class="save-settings" ng-click="saveSetting('display_name')">
Save
</div>
</div>
</div>
</div>
</div>
The idea behind shutSetting() is to shut the editing panel setting-edit-row and restore the original data that I got from the api. However, when I do this, it shows me the temp variable being the same as the $scope.userObj variable. I added a $scope.showVal function to show the variables on change of the input form:
$scope.showVal = function(){
console.log({userObj: $scope.userObj});
console.log({temp: userObjTemp});
}
For some reason, both variables are getting updated. How do I fix this as I've never faced something similar before.
The problem is that you are referencing objects instead of copying them. Thus
$scope.userObj.user = data.response;
userObjTemp.user = data.response;
points all to the same object. Then, when you update one of the two also the other gets updated.
userObjTemp.user = angular.copy(data.response)
this makes a copy.
Just in case: https://jsfiddle.net/qzj0w2Lb/
The problem is, that both of your variables are referencing the same object data.response. Depending on the object, you could use $.extend(true, {}, data.response); to get a clone of the object.
Be aware though, that this is not a true "deep copy" when custom objects are involved!
I have multiple same class divs that produce an array and a script that puts them into lists.
I would like to hide a JSON array object from briefly flashing (unprocessed) on the page before the script can process it into lists.
So I put them into a hidden div and the each function stops working.
The .hid divs actually contain:
<%=getCurrentAttribute('item','lists')%> that produce the JSON array.
<div class="hid" style="display:none;">[{"k":"Model","v":"AB"},{"k":"Color","v":"green"}]</div>
<div class="overview"></div>
<div class="hid" style="display:none;">[{"k":"Model","v":"AC"},{"k":"Color","v":"blue"}]</div>
<div class="overview"></div>
<div class="hid" style="display:none;">[{"k":"Model","v":"AD"},{"k":"Color","v":"red"}]</div>
<div class="overview"></div>
My script
jQuery('.hid').each(function () {
var $data = jQuery(this), spec,
specs = jQuery.parseJSON($data.html());
jQuery(".overview").html('<div class="bullet_spec"></div>');
jQuery.each(specs, function () {
jQuery(".overview").children('div').append('<div class="specs"><span class="label">' + this.k + ':</span><span class="value"> ' + this.v + '</span></div>');
});
{
}
});
http://jsfiddle.net/Qta2p/
This is the start of an inventory system I am working on. Basically it takes an array with items and quantities in a compressed form and outputs the items into an item div.
Running the below produces no error:
$('.item_amount').html(collection[itemName].amo);
Adding the get() method after the selector like so:
$('.item_amount').get(i).html(collection[itemName].amo);
produces "$(".item_amount").get(i).html is not a function".
This is what the line is altering:
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
The line that is causing the error is located in a for loop that loops through all the keys in an array. Then outputs the item quantity from the array in the item_amount div based on the index stored in the variable "i". The for loop also creates an object for each item in the array and puts in the a collection object.
Full code below:
<body>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<script type="text/javascript">
var collection = new Object();
function makeItem(itemName, id, amo) {
collection[itemName] = new item(id, amo);
}
function item(id, amo) {
this.id = id;
this.amo = amo;
}
var inventoryCom = "368.9,366.15,384.32"; //compressed inventory
var inventoryArr = inventoryCom.split(',');
for(var i=0; i < inventoryArr.length; i++) {
var itemName = 'item' + (i + 1); //unique name for each item
var itemArr = inventoryArr[i].split('.');
makeItem(itemName, itemArr[0], itemArr[1]);
$('.item_amount').get(i).html(collection[itemName].amo);
}
</script>
</body>
.get(i) returns DOM element, which doesn't have .html() method - that's what js engine wants to say to you.
You need to use .eq(i) instead. Like
$('.item_amount').eq(i).html(collection[itemName].amo);
or
$('.item_amount:eq(' + i + ')').html(collection[itemName].amo);
This line may be a problem
var itemName = 'item' + (i + 1); //
This may increment the array count out of the upper bound. check the itemName value.
Also try to add an alert for this
collection[itemName].amo
I have a product block in a template like this :
<script type="text/x-handlebars-template" id="tmpl-person">
<div class="product">
<!-- Product details here -->
</div>
</script>
What I want to do is if from the array of person I get as data , after every three persons , I want to insert a container called <div class="row-fluid"></div> and three persons inside it.. then a row-fluid container and three persons inside it. How can I achieve this using helpers ? Thanks for help.
You could use something like this
Handlebars.registerHelper('each', function(context, block) {
var ret = "";
for(var i=0, j=context.length; i<j; i++) {
ret = ret + "<li>" + block(context[i]) + "</li>";
}
if( i % 3 == 0)
ret = ret + <div class="row-fluid"></div>
return ret;
});
And you could define your custom iterator like following
<script type="text/x-handlebars-template" id="tmpl-person">
{{#each productInfo}}
<div class="product">
<!-- Product details here -->
</div>
{{/each}}
</script>