Get active menu element and display its title AngularJS - javascript

How to retrieve the element class and display its name?
I read that I can use sth like:
var elementResult = element[0].getElementsByClassName('menu-item-active');
console.log('element[0].getElementsByClassName: ', elementResult);
JSON :
{
"title": "Fruits",
"mainmenu": [
{
"id": "apples",
"title": "Apples",
"href": "#/apples",
"act": "menu-item-active"
},
{
"id": "bananas",
"title": "Bananas",
"submenu": [
{
"id": "banana-box",
"title": "Banana Box",
"href": "#/banana-box",
"act": "menu-item-active"
}
]
}
]
}
I have a directive
.directive('dir', function () {
return {
restrict: 'E',
template: "<nav class=\"navbar navbar-inverse navbar-fixed-top\" role=\"navigation\" id=\"nav-bar\">"
+ "<div class=\"container-fluid\">"
+ "<div class=\"navbar-header\">"
+ "<span class=\"navbar-brand\" >{{title}} </span>"
+ "</div>"
+ "<ul class=\"nav navbar-nav\" ng-repeat=\"item in mainmenu\">"
+ "<li>"
+ "{{item.title}}"
+ "</li>"
+ "</ul>"
+ "</div>"
+ "</nav>"
}
});
And the controller:
.module('menu').controller('menuCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('MenuItems.json').success(function (data) {
$scope.mainmenu = data.mainmenu;
$scope.title = data.title;
});
}]);
What I want to achieve:
when I will be on the each site/subsite and I want to display its name as {{title}} in my site
I tried to use the elementResult but I don't know how to check if the element is menu-item-active. I thought about using the ng-if statement, but I don't know how to handle it.
For.ex.
ng-if="elementResult has class 'menu-item-active' then display its 'title' as {{title}} in menu bar

In dom, getElementByClassName returns NodeList.
var nodeList = element[0].getElementsByClassName('menu-item-active');
So then you have to iterate over nodes. You can use it's length property.
for ( var i = 0 ; i < nodeList.length ; i++ )
if ( nodeList[i].className == 'menu-item-active' )
var elem = $scope.findByClassName('menu-item-active');
and in your controller write scope method:
$scope.findByClassName = function(id){
for ( var i = 0 ; i < jsonArray.length ; i++ )
if ( jsonArray[i].mainmenu.act == id )
return jsonArray[i].title;
}
Also prepare proper JSON file - key value pairs and arrays of objects ( these starting with { and ending with } ).
Also, in Angular you can pass to param to a page/view, so you can use routes and $routeParam service must be dependency injected in your controller. Then for page "new/3" you ask for "$routeParams.id" and you will get 3.

Related

How to populate div tables and dropdownboxes with JSON and Javascript?

I've been trying to populate div tables with dummy JSON data but I cannot seem to do it. What I want to do is display certain data depending of the selection in a dropdownbox. Also I need to create new row with a new dropdownbox when an item is selected. Could you give me some advice of what's the best way to do it. I'm able to create something close to what I need in Angular but I need it in pure JavaScript. Thanks in advance!
structure of my div tables
Suppose in data you have json object
var data = [
{
"line": "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
"author": "Brian W. Kernighan",
"num" : ["1","2","3"]
},
{
"line": "Walking on water and developing software from a specification are easy if both are frozen.",
"author": "Edward V Berard",
"num" : ["5","0","15"]
},
{
"line": "It always takes longer than you expect, even when you take into account Hofstadter's Law.",
"author": "Hofstadter's Law",
"num" : ["15","222","301"]
}];
and you want to populate all authors in above json object to table and num into respective dropdown element of table-row. Then following populateHTML() function populate object to table and num into respective dropdown element of table-row as shown in below image .
function populateHTML(data) {
if (typeof(data) == 'object') {
document.write('<table>');
for (var i in data) {
document.write('<tr><td>'+data[i].author+'</td><td><select>');
for(var j in data[i].num){
document.write('<option>' +data[i].num[j]+ '</option>');
}
document.write('</select></td></tr>');
}
document.write('</tr></table>');
} else {
document.write(' => ' + data);
}
}
This can be achieved with the following code: You can also check an example here: http://skillcram.com/JS_DivTable.htm
<script type="text/javascript" >
function populateTable() {
var tableData = {
products : [
{"id": 100,"name":"Laptop", "qty":1,"status": ["Delivered","Damaged","Missing"]},
{"id": 200,"name":"Monitor", "qty":2,"status":["Refused","Partial"]}
]
}
var tableBody = document.getElementsByClassName("divTableBody");
for (i in tableData.products){
tableBody[0].innerHTML += "<div class=\"divTableRow\"> " +
"<div class=\"divTableRowCell\">"+ tableData.products[i].id +" </div> " +
"<div class=\"divTableRowCell\">"+ tableData.products[i].name +" </div> " +
"<div class=\"divTableRowCell\">"+ tableData.products[i].qty +" </div> "+
"<div class=\"divTableRowCell\">"+ getSelectHTMl(tableData.products[i].status) +
" </div> "+
"</div>";
}
}
function getSelectHTMl(status) {
selectHTMlStr = "<select> ";
for (j in status){
selectHTMlStr +=
"<option value=\""+ status[j]+ "\" id=\"itemStatus\" >"+status[j]+ " </option>" ;
}
selectHTMlStr += "</select>" ;
return selectHTMlStr;
}
</script>

Close multiselect dropdown when user clicks outside (different situation) [duplicate]

This question already has answers here:
AngularJS dropdown directive hide when clicking outside
(9 answers)
Closed 7 years ago.
Please refer to this jsfiddle. http://jsfiddle.net/jaredwilli/vUSPu/
This is for multi select dropdown. User selects options available in the drop and clicks outside the dropdown menu. The dropdown list doesnt close unless you click on the dropdown menu itself.
Is there any way to hide the dropdown when user clicks anywhere else away from dropdown list.
<div ng-app="myApp" ng-controller="AppCtrl">
<dropdown-multiselect pre-selected="member.roles" model="selected_items" options="roles"></dropdown-multiselect>
<pre>selected roles = {{selected_items | json}}</pre>
'use strict';
var app = angular.module('myApp', ['app.directives']);
app.controller('AppCtrl', function($scope){
$scope.roles = [
{"id": 1, "name": "Manager", "assignable": true},
{"id": 2, "name": "Developer", "assignable": true},
{"id": 3, "name": "Reporter", "assignable": true}
];
$scope.member = {roles: []};
$scope.selected_items = [];
});
var app_directives = angular.module('app.directives', []);
app_directives.directive('dropdownMultiselect', function(){
return {
restrict: 'E',
scope:{
model: '=',
options: '=',
pre_selected: '=preSelected'
},
template: "<div class='btn-group' data-ng-class='{open: open}'>"+
"<button class='btn btn-small'>Select</button>"+
"<button class='btn btn-small dropdown-toggle' data-ng-click='open=!open;openDropdown()'><span class='caret'></span></button>"+
"<ul class='dropdown-menu' aria-labelledby='dropdownMenu'>" +
"<li><a data-ng-click='selectAll()'><i class='icon-ok-sign'></i> Check All</a></li>" +
"<li><a data-ng-click='deselectAll();'><i class='icon-remove-sign'></i> Uncheck All</a></li>" +
"<li class='divider'></li>" +
"<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'>{{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +
"</ul>" +
"</div>" ,
controller: function($scope){
$scope.openDropdown = function(){
$scope.selected_items = [];
for(var i=0; i<$scope.pre_selected.length; i++){ $scope.selected_items.push($scope.pre_selected[i].id);
}
};
$scope.selectAll = function () {
$scope.model = _.pluck($scope.options, 'id');
console.log($scope.model);
};
$scope.deselectAll = function() {
$scope.model=[];
console.log($scope.model);
};
$scope.setSelectedItem = function(){
var id = this.option.id;
if (_.contains($scope.model, id)) {
$scope.model = _.without($scope.model, id);
} else {
$scope.model.push(id);
}
console.log($scope.model);
return false;
};
$scope.isChecked = function (id) {
if (_.contains($scope.model, id)) {
return 'icon-ok pull-right';
}
return false;
};
}
}
});
I've tried your jsFiddle i see what you mean. I think this would help you.
With a little bit of searching alot can be found :)
AngularJS dropdown directive hide when clicking outside

jQuery Mobile load new data only

I'm working on this project for learning purposes. The tasks for now are very simple:
Populate data from DB using $.getJSON.
Check every 'n' seconds for new data and append it to the list.
Notify user about new data changes.
Here is the example of where I got so far: ( JSBin /Don't forget to run js)
All the issues will be visible when running the example.
Here is the JS code that i have:
$(document).bind('pageinit', function(){
var $myList = $( "#myList" );
var newItems = [];
function loadList(){
$.getJSON("http://jsbin.com/vayeni/2.js",function(data){
$.each(data, function( index, value ) {
newItems.push( "<li><a>" + value.airline + "</a></li>" );
if(data>newItems){
alert('New Entry');
data=newItems;
}
});
$myList.append( newItems.join( "" ) );
$myList.listview( "refresh" );
setTimeout(loadList,1000);
});
}
loadList();
});
Thanks for your help !
Your data comparison is not correct.
You are comapring this:
<li><a>JetBlue</a></li>
<li><a>Continental</a></li>
...
to this:
{
"id": "1",
"airline": "JetBlue",
"number": "222",
"people": "3",
"time": "12:20"
},
{
"id": "2",
"airline": "Continental",
"number": "222",
"people": "5",
"time": "23:21"
},
There will be always inequality.
You should use another approach. For example, if the id field from your JSON array is an unique one you can attach it to each item from the unordered list as an id attribute. For example:
newItems.push( "<li id=\"" + value.id + "\"><a>" + value.airline + "</a></li>" );
This way, at each iteration you can check if the incomming JSON item already exists into your list and add it when there is no match. Eg:
if (!$myList.find('#' + value.id).length) {
newItems.push( "<li id=\" + value.id + \"><a>" + value.airline + "</a></li>" );
}
Finally, you can append the newItems contents directly if there are items inside:
if (newItems.length > 0) {
$myList.append( newItems.join( "" ) );
}
Here is the edited snippet: JSBin

jQuery is not pulling data from a JSON and adding the data - What's wrong with my code?

I have a JSON file set up with data that, when a user on my site selects a music genre from a dropdown menu, songs of that music genre (the songs are stored in the JSON file, along with the artist) will be displayed in a combo box on my site. Sadly, this is not going according to plan.
I know that this error is based around some mistake that I am making, but I don't know where exactly! My browser's console is saying, "Uncaught TypeError: Cannot read property 'undefined' of undefined" on the following statement:
var selectedValue = dropDown.options[dropDown.selectedIndex].value;
However, I don't know what that means or if it's actually a legitimate runtime error. Anyways, here is my code. I would really appreciate it if you awesome people could look over my code and see what you think may be causing my code to not act in the way that I want to it to act (detailed in the first paragraph) :)
JSON
{
"library":
[
// ROCK
{
"title": "Your Love",
"artist": "The Outfield"
},
{
"title": "Voodoo Child",
"artist": "Jimi Hendrix"
},
{
"title": "When I'm Gone",
"artist": "Three Doors Down"
},
// ALTERNATIVE
{
"title": "Jumper",
"artist": "Third Eye Blind"
},
{
"title": "One Week",
"artist": "Barenaked Ladies"
},
{
"title": "The Middle",
"artist": "Jimmy Eat World"
}
]
}
JavaScript
$(document).ready(function()
{
// Declare our needed variables
var dropDown = $("#music-genre"); // <select id="music-genre">...</select>
var selectedValue = dropDown.options[dropDown.selectedIndex].value;
var target = $('#song'); // <select multiple id="song">...</select>
// If "Alternative" is chosen, choose the alternative songs
// I didn't add a conditional statement for choosing "Rock" because it's the same
if (selectedValue == "Alternative")
{
// "data/music.json" is the location of my JSON file
$.getJSON("data/music.json", function(data)
{
$.each(data, function(key, val)
{
target.innerHTML += '<option value="' + val.title + '">' + val.title + 'by ' + val.artist + '</option>';
}); // END $.each
}); // END $.getJSON
} // END if
}); // END ready()
HTML
<!-- Drop Down -->
<select id="music-genre">
<option id="rock" value="rock">Rock</option>
<option id="alternative" value="alternative">Alternative</option>
</select>
<!-- Combo Box -->
<select multiple id="song">
<!-- "Select one or more" is disabled because I don't want users selecting it -->
<option value="select" disabled>Select one or more</option>
</select>
Your the data you want from your returned JSON is in the library array, so you need to use data.library.
Also note that target will be a jQuery object which does not have a innerHTML property, so you need to use append instead:
$.each(data.library, function(key, val) {
target.append('<option value="' + val.title + '">' + val.title + 'by ' + val.artist + '</option>');
})
Finally as others mentioned you can use the val() property on a select element to get the selected value:
var selectedValue = $("#music-genre").val();
Try to use it like this:
JSON:
{
"library": {
"rock": [
{
"title": "Your Love",
"artist": "The Outfield"
},
{
"title": "Voodoo Child",
"artist": "Jimi Hendrix"
},
{
"title": "When I'm Gone",
"artist": "Three Doors Down"
}
],
"alternative": [
{
"title": "Jumper",
"artist": "Third Eye Blind"
},
{
"title": "One Week",
"artist": "Barenaked Ladies"
},
{
"title": "The Middle",
"artist": "Jimmy Eat World"
}
]
}
JAVASCRIPT:
$(function(){
// Declare our needed variables
var dropDown = $("#music-genre"); // <select id="music-genre">...</select>
// var selectedValue = dropDown.options[dropDown.selectedIndex].value;
var target = $('#song'); // <select multiple id="song">...</select>
dropDown.on("change", function(){
var genre = $(this).val();
var html = '';
$.getJSON("test.json", function(data){
$.each(data.library[genre], function(key, val){
html += '<option value="' + val.title + '">' + val.title + 'by ' + val.artist + '</option>'; // Save whole html in a var
}); // END $.each*/
target.html(html); // append it in target div
}); // END $.getJSON
});
}); // END ready()
Try to use:
var selectedValue = dropDown.find(':selected').val();
or:
var selectedValue = dropDown.val();
instead of:
var selectedValue = dropDown.options[dropDown.selectedIndex].value;
since dropDown is a jQuery object which required you to use jQuery method here.
Also note that data contains library array, so you need to access this array to get the value inside:
$.each(data.library, function(key, val) {
target.innerHTML += '<option value="' + val.title + '">' + val.title + 'by ' + val.artist + '</option>';
});

Javascript - Populating a form dynamically based on one object and filling in the values from another object

I have a JSON object that I use as a Template for all available Fields that can be added to an element in my Object that is used to Store the values.
I have another Object that holds values. The k,v of this Object storing all the values was not generated in my application. It is handed to me and I need to populate that value in a form that is created dynamically based on my JSON which defines all availabl keys for a given element. Its best I show you my demo app.
Demo: http://jsfiddle.net/bGxFC/15/
1. Click "Button_2" label - Notice how it populates a form with 5 k,v inputs
2.Now click "Button_1" label - Notice how this has 6 k,v inputs
3. Both of these are "Type": "Button" but "Button_2" is missing 'Transition' from its inputs
4This is where my 'var controls' object comes in. It defines all the available option that each type can have.
The Problem
I need to alter my code to use the values from 'objStr' and place them into a form that was created by 'controls'. And once I add a value to an empty input(i.e.The 'Transition' input in "Button_2") it will be saved back to 'objStr'.
Here is my code:
var controls = {
"Button":{"Type": "", "Transition": "","BackgroundImage": "","Position": "","Width": "","Height": ""},
"Image":{"Type": "","BackgroundImage": "","Position": "","Width": "","Height": ""},
"Label":{"Type": "","Position": "","Width": "","Height": "","Text": "","FontSize":"","Color": "", "FontType": ""}
};
objStr = {
"View_1":
{
"Image_1":{
"Type":"Image",
"BackgroundImage":"Image.gif",
"Position":[0,0],
"Width":320,
"Height":480
},
"Button_1":{
"Type":"Button",
"BackgroundImage":"Button.gif",
"Transition":"View2",
"Position":[49,80],
"Width":216,
"Height":71
},
"Button_2":{
"Type":"Button",
"BackgroundImage":"Button2.gif",
"Position":[65,217],
"Width":188,
"Height":134},
"Label_1":{
"Type":"Label",
"Position":[106,91],
"Width":96,
"Height":34,
"Text":"Button",
"FontSize":32,
"Color":[0.12549,0.298039,0.364706,1]
}
}
};
$(document).ready(function () {
var $objectList = $('<div id="main" />').appendTo($('#main'));
$.each(objStr.View_1, function(k, v) {
$('<div/>').append(k).appendTo($objectList).on('click', function(){
var $wrapper = $('#form .wrapper').empty();
if(typeof v === 'string') {
$('<div class="item" />').append('<span class="key">' + k + '</span>' + '<input value="' + v + '"/>').appendTo($wrapper);
}
else {//object
$('<h3 class="formHeading" />').append(k).appendTo($wrapper);
$.each(v, function(key, val) {
$('<div class="item" />').append('<span class="key">' + key + '</span>' + '<input value="' + val + '"/>').appendTo($wrapper);
});
}
$("<button>Save</button>").appendTo($wrapper).on('click', function() {
if(typeof v === 'string') {
v = $(this).closest(".wrapper").find("input").val();
}
else {//object
$(this).closest(".wrapper").find(".item").each(function(i, div) {
var $div = $(div),
key = $div.find(".key").text(),
val = $div.find("input").val();
v[key] = val;
});
}
});
});
});
});

Categories

Resources