dimanche 19 avril 2015

Tracking Google Analytics events with Angulartics

I am using Angulartics to do the tracking on my website. http://ift.tt/1stwwJB


Events are tracked on mixpanel as well as google analytics. Mixpanel events are tracked as desired. However, Google analytics does receive the page views but does not track any events at all. I know that GA requires a "category" as well as a "action" to be set for each event.


So my event tracking basically looks like this,



<a ng-click="bookingModal($parent.$index)" href="{{trip.bookings[0].providers[0].url}}" target="_blank">Test </a>


Basically, I have a simple ng-click on my event (some events can be fired without clicking).


in my controller I have the following:



$scope.bookingModal=function (trip){
var clickedIndex=trip;
var detailTracker={
eventCategory: 'bookingModalClicked',
eventAction: 'bookingModalClicked Action',
userMail:Auth.user().email,
userName:Auth.user().user,
clickedIndex: clickedIndex
};
$analytics.eventTrack('clickBooking',detailTracker);


This tracking works perfectly fine with mixpanel, but events are not tracked with GA. What am I doing wrong? I dont seem to find my mistake.


ng-click - after click do function and redirect

I have little problem.


I want to create ng-click with redirect, but before redirect I need to post some data.


My html code :



<a href="/test" ng-click="updateData($event)">Go</a>


My angular updateData function :



$scope.updateData = function($event){

$event.preventDefault();

$http.post(someAddress, $scope.data)
.success(function(){
// on success redirect
});
};


I found somethings like this scope.$eval(clickAction); but I don;t know how I should use it.


I can't use only redirect without JS because I have 2 different forms.


Angular NVD3 scatterChart

I have just started using angular NVD3.


Here is a scatterChart I made with JavaScript, but I cannot find out the reason why it just shows the points with y-value <= 9 whereas there are many points like {"x":"52","y":"17"}.


Would anyone give me some advice?


Inserting html div value in js var

I have the following code at bottom of page to update amount (p_amount) and package id (pack_id) (all codes are in same page)



jQuery.ajax({
url : ajaxurl,
dataType : "json",
type : "post",
data : search_params,
success : function(response){
if(response.code=='success'){
jQuery('#coupon-result').html('<img src="<?php echo WP_iv_membership_URLPATH; ?>admin/files/images/right_icon.png">');
}else{
jQuery('#coupon-result').html('<img src="<?php echo WP_iv_membership_URLPATH; ?>admin/files/images/wrong_16x16.png">');
}
jQuery('#p_amount').html(response.p_amount);

}


after this, It updates the value here



<div class="col-md-8 col-xs-8 col-sm-8 " id="p_amount">


and here in the middle of page i am using js to send values over my payment gateway provider, I want to insert the updated value of amount(p_amount) inside (var amount), but it never updates



<div class="checkout">
<script type="text/javascript">
var amount = 'p_amount';
var currency = 'USD';

SOLUTION: It seemed that my .get() function invoked before I could update the variable 'something' and therefore it didn't show the updated variable.


When I tested it on the real page it worked like a charm :)


final FIDDLE


note: I did add a return to the set function to immediately update the view.




UPDATE: got my factory working alright but can't get the value bound to the factory .set() function. FIDDLE




I’m building a manual to install a USB-network connector and need to store some variables to show the right content across multiple pages (within the same controller tough).


After doing some research it seems 'services' are the right way to do this however I can't get them to work.


It does work when I put the function inside the controller itself but it get's reset to '[]' again when I change page.


function inside controller as I have it right now is:



$scope.isActiveSystem = [];

$scope.activeSystem = function(name) {
$scope.isActiveSystem = name.value;
}


Can someone point me in the right direction how to put this inside a service or give me an example to study so I can understand better what's going on?


Also, should I store my data in a factory or some service?


My attempt to make a service: FIDDLE


One ajax call for more than one div content and page?

I use this code to make ajax call to change the content of div in main page without reloading the page :



function ajaxcall()
{
$.ajax({
type: "POST",
url: "/create.php",
success: function( returnedData ) {
$( '#container' ).html( returnedData );
}
});
}


and I call it like that :



<p><a onclick="ajaxcall()" >Create</a></p>


The issue is very complicated because I have to call 4 pages in the same div :



create.hmtl ; update.html; delete.html ; read.html


Also I have 2 different forms in the same page that required the same thing, I mean I should do the same thing for the second form with another div "container-1",then I have 2 div for exmaple in create.html :


create.html :



<div id="container">
....
</div>

<div id="container-1">
....
</div>


So I call create.html everytime but different div for different form, the question is to use a minimum clean code to do all what I explained above?


Correct construction SPA with Knockout

I just want to know some details during construction SPA with Knockout. I make main page with MainMenu (ul) and MainContent (div). MainContent is empty. From main menu I can invoke following commands: Home page, Product list, New product, About page and etc.



For example I invoke Product list.


1. I get ProductList HTML (ul with foreach binding) from a server.

2. Insert ProductList (ul) in MainContent (div).

3. Create ListViewModel, apply binding to MainContent (div).

4. Get data from a server (10 objects) and put the data to observable array in ListViewModel.

Everything is fine. Browser show me all 10 objects in ProductList (ul). Then from the main menu I invoke about page:


1) Get AboutPage HTML from the server.

2) Insert AboutPage (HTML) in MainContent (div).

Everything is fine. Browser show me about page.



Then I want to invoke Product list again. I click Product list but Browser show me only 1 product (without any data in it) in ProductList (ul) in ProductList although there are no errors.


This way of construction is correct? Some advice? Should I re create ViewModel of Product list. Should I re apply bindings?


Google Search Engine Two Page Layout Not Working

I've added a search engine in my site using the google's custom search engine. I chose the two page layout because I what I want is that the search box will be at the homepage and its result will be shown in another page. But it won't work on mine. Whenever I try to search something it won't show results and it won't go to the page. What will I do? Please help me. Thank you.


for search box



<script>
(function() {
var cx = 'XXXXXXXX:XXXXXXX';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchbox-only></gcse:searchbox-only>


for results



<script>
(function() {
var cx = 'XXXXXXXX:XXXXXXX';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchresults-only></gcse:searchresults-only>


This is my preview website


nodejs loops and arrays

Hey everyone i cant seem to grasp the arrays function in nodejs and am having a few problems programming it to work the way i want


what i am doing is getting json info from an api and using that for the arrays.


i would like it formatted like so



array = [ { Coin:{Balance: 0, Available: 0, Pending: 0, Exchange: 0} ]


the output from the API looks like this



[ { Currency: 'BTC',
Balance: 3.0000000000000004e-8,
Available: 3.0000000000000004e-8,
Pending: 0,
CryptoAddress: '1G29t11ioGa5cmWJKLeanbNz1TA77eS1gK' },
{ Currency: 'DGB',
Balance: 0,
Available: 0,
Pending: 0,
CryptoAddress: 'DTcrZApNRDmq41bhcPcZdhhApaLQGr7nfj' }
] }


and the script im using to try and add them to a new array is





var redis = require('redis');
client = redis.createClient()

var bittrex = require('node.bittrex.api');
bittrex.options({
'apikey': 'KEY',
'apisecret': 'SECRET',
'stream': true,
'verbose': true,
'cleartext': true,
'baseUrl': 'http://ift.tt/1MiVHVL'
});


bittrex.getbalances(function(data) {
console.log(data);
array = [];
for (var coin in data.result) {
Name = data.result[coin].Currency;
array.push(Name);

array[Name].Balance.push(data.result[coin].Balance);

array[Name].Available.push(data.result[coin].Available);
array[Name].Pending.push(data.result[coin].Pending);


client.hget("Exchange_Rates", data.result[coin].Currency, function(err, exchange) {
array[Name].Exchange.push(exchange);
});

};

console.log(array);


for (var sell in array) {
bittrex.sendCustomRequest('http://ift.tt/1Hm0ciZ' + sell + '&quantity=' + array[Name].Available + '&rate=' + array[Name].Exchange, function(data) {
console.log(data);
}, true);
};


});



This is the current error returned

/home/alastair/cryptsy.js:22 array[Name].Balance.push(data.result[coin].Balance); ^ TypeError: Cannot read property 'Balance' of undefined at /home/alastair/cryptsy.js:22:12 at /home/alastair/node_modules/http://ift.tt/1G7fS8o at Stream.write (/home/alastair/node_modules/http://ift.tt/1Hm0cj1) at Stream.stream.write (/home/alastair/node_modules/http://ift.tt/1G7fR4g) at Stream.ondata (stream.js:51:26) at Stream.EventEmitter.emit (events.js:95:17) at drain (/home/alastair/node_modules/http://ift.tt/1Hm09Uu) at Stream.stream.queue.stream.push (/home/alastair/node_modules/http://ift.tt/1G7fR4i) at Parser.parser.onToken (/home/alastair/node_modules/http://ift.tt/1Hm09Uy) at Parser.proto.write (/home/alastair/node_modules/http://ift.tt/1G7fR4k)


How to add multiple input fields to jQuery Taggd plugin?

I am using the jQuery Taggd Plugin


Please see also Taggd Project page / examples


I am using the plugin with edit: true. You can tag something in a image and add a text note to it, but i would like to be able to add a Title and a Description for a tag. I've been trying to modif the plugin for some time now, but nothing seems to do what i want.


I want both the input fields to keep the values when you toggle the tag.


I hope someone can shine a light or get me going in the right direction?



/*!
* jQuery Taggd
* A helpful plugin that helps you adding 'tags' on images.
*
* License: MIT
*/

(function($) {
'use strict';

var defaults = {
edit: false,

align: {
x: 'center',
y: 'center'
},

handlers: {},

offset: {
left: 0,
top: 0
},

strings: {
save: '&#x2713;',
delete: '&#x00D7;'
}
};

var methods = {
show: function() {
var $this = $(this),
$label = $this.next();

$this.addClass('active');
$label.addClass('show').find('input').focus();
},

hide: function() {
var $this = $(this);

$this.removeClass('active');
$this.next().removeClass('show');
},

toggle: function() {
var $hover = $(this).next();

if($hover.hasClass('show')) {
methods.hide.call(this);
} else {
methods.show.call(this);
}
}
};


/****************************************************************
* TAGGD
****************************************************************/

var Taggd = function(element, options, data) {
var _this = this;

if(options.edit) {
options.handlers = {
click: function() {
_this.hide();
methods.show.call(this);
}
};
}

this.element = $(element);
this.options = $.extend(true, {}, defaults, options);
this.data = data;
this.initialized = false;

if(!this.element.height() || !this.element.width()) {
this.element.on('load', _this.initialize.bind(this));
} else this.initialize();
};


/****************************************************************
* INITIALISATION
****************************************************************/

Taggd.prototype.initialize = function() {
var _this = this;

this.initialized = true;

this.initWrapper();
this.addDOM();

if(this.options.edit) {
this.element.on('click', function(e) {
var poffset = $(this).parent().offset(),
x = (e.pageX - poffset.left) / _this.element.width(),
y = (e.pageY - poffset.top) / _this.element.height();

_this.addData({
x: x,
y: y,
text: ''
});

_this.show(_this.data.length - 1);
});
}

$(window).resize(function() {
_this.updateDOM();
});
};

Taggd.prototype.initWrapper = function() {
var wrapper = $('<div class="taggd-wrapper" />');
this.element.wrap(wrapper);

this.wrapper = this.element.parent('.taggd-wrapper');
};

Taggd.prototype.alterDOM = function() {
var _this = this;

this.wrapper.find('.taggd-item-hover').each(function() {
var $e = $(this),

$input = $('<input type="text" size="16" />')
.val($e.text()),
$button_ok = $('<button />')
.html(_this.options.strings.save),
$button_delete = $('<button />')
.html(_this.options.strings.delete);

$button_ok.on('click', function() {
_this.hide();
});

$button_delete.on('click', function() {
var x = $e.attr('data-x'),
y = $e.attr('data-y');

_this.data = $.grep(_this.data, function(v) {
return v.x != x || v.y != y;
});

_this.addDOM();
_this.element.triggerHandler('change');
});

$input.on('change', function() {
var x = $e.attr('data-x'),
y = $e.attr('data-y'),
item = $.grep(_this.data, function(v) {
return v.x == x && v.y == y;
}).pop();

if(item) item.text = $input.val();

_this.addDOM();
_this.element.triggerHandler('change');
});

$e.empty().append($input, $button_ok, $button_delete);
});

_this.updateDOM();
};

/****************************************************************
* DATA MANAGEMENT
****************************************************************/

Taggd.prototype.addData = function(data) {
if($.isArray(data)) {
this.data = $.merge(this.data, data);
} else {
this.data.push(data);
}

if(this.initialized) {
this.addDOM();
this.element.triggerHandler('change');
}
};

Taggd.prototype.setData = function(data) {
this.data = data;

if(this.initialized) {
this.addDOM();
}
};

Taggd.prototype.clear = function() {
if(!this.initialized) return;
this.wrapper.find('.taggd-item, .taggd-item-hover').remove();
};


/****************************************************************
* EVENTS
****************************************************************/

Taggd.prototype.on = function(event, handler) {
if(
typeof event !== 'string' ||
typeof handler !== 'function'
) return;

this.element.on(event, handler);
};


/****************************************************************
* TAGS MANAGEMENT
****************************************************************/

Taggd.prototype.iterateTags = function(a, yep) {
var func;

if($.isNumeric(a)) {
func = function(i, e) { return a === i; };
} else if(typeof a === 'string') {
func = function(i, e) { return $(e).is(a); }
} else if($.isArray(a)) {
func = function(i, e) {
var $e = $(e);
var result = false;

$.each(a, function(ai, ae) {
if(
i === ai ||
e === ae ||
$e.is(ae)
) {
result = true;
return false;
}
});

return result;
}
} else if(typeof a === 'object') {
func = function(i, e) {
var $e = $(e);
return $e.is(a);
};
} else if($.isFunction(a)) {
func = a;
} else if(!a) {
func = function() { return true; }
} else return this;

this.wrapper.find('.taggd-item').each(function(i, e) {
if(typeof yep === 'function' && func.call(this, i, e)) {
yep.call(this, i, e);
}
});

return this;
};

Taggd.prototype.show = function(a) {
return this.iterateTags(a, methods.show);
};

Taggd.prototype.hide = function(a) {
return this.iterateTags(a, methods.hide);
};

Taggd.prototype.toggle = function(a) {
return this.iterateTags(a, methods.toggle);
};

/****************************************************************
* CLEANING UP
****************************************************************/

Taggd.prototype.dispose = function() {
this.clear();
this.element.unwrap(this.wrapper);
};


/****************************************************************
* SEMI-PRIVATE
****************************************************************/

Taggd.prototype.addDOM = function() {
var _this = this;

this.clear();
this.element.css({ height: 'auto', width: 'auto' });

var height = this.element.height();
var width = this.element.width();

$.each(this.data, function(i, v) {
var $item = $('<span />');
var $hover;

if(
v.x > 1 && v.x % 1 === 0 &&
v.y > 1 && v.y % 1 === 0
) {
v.x = v.x / width;
v.y = v.y / height;
}

if(typeof v.attributes === 'object') {
$item.attr(v.attributes);
}

$item.attr({
'data-x': v.x,
'data-y': v.y
});

$item.css('position', 'absolute');
$item.addClass('taggd-item');

_this.wrapper.append($item);

if(typeof v.text === 'string' && (v.text.length > 0 || _this.options.edit)) {
$hover = $('<span class="taggd-item-hover" style="position: absolute;" />').html(v.text);

$hover.attr({
'data-x': v.x,
'data-y': v.y
});

_this.wrapper.append($hover);
}

if(typeof _this.options.handlers === 'object') {
$.each(_this.options.handlers, function(event, func) {
var handler;

if(typeof func === 'string' && methods[func]) {
handler = methods[func];
} else if(typeof func === 'function') {
handler = func;
}

$item.on(event, function(e) {
if(!handler) return;
handler.call($item, e, _this.data[i]);
});
});
}
});

this.element.removeAttr('style');

if(this.options.edit) {
this.alterDOM();
}

this.updateDOM();
};

Taggd.prototype.updateDOM = function() {
var _this = this;

this.wrapper.removeAttr('style').css({
height: this.element.height(),
width: this.element.width()
});

this.wrapper.find('span').each(function(i, e) {
var $el = $(e);

var left = $el.attr('data-x') * _this.element.width();
var top = $el.attr('data-y') * _this.element.height();

if($el.hasClass('taggd-item')) {
$el.css({
left: left - $el.outerWidth(true) / 2,
top: top - $el.outerHeight(true) / 2
});
} else if($el.hasClass('taggd-item-hover')) {
if(_this.options.align.x === 'center') {
left -= $el.outerWidth(true) / 2;
} else if(_this.options.align.x === 'right') {
left -= $el.outerWidth(true);
}

if(_this.options.align.y === 'center') {
top -= $el.outerHeight(true) / 2;
} else if(_this.options.align.y === 'bottom') {
top -= $el.outerHeight(true);
}

$el.attr('data-align', $el.outerWidth(true));

$el.css({
left: left + _this.options.offset.left,
top: top + _this.options.offset.top
});
}
});
};


/****************************************************************
* JQUERY LINK
****************************************************************/

$.fn.taggd = function(options, data) {
return new Taggd(this, options, data);
};
})(jQuery);


What do i have to add to the code above to get this working?


Thank you very much!!!


How does this fiddle each just return one value at each time?

I see this fiddle that was answered to this question, I know how does each work in jquery and it will do one thing on all element that we gave it. But in this fiddle it just return one thing according to scroll, I made something like that in my own computer and in my own project but it was returning all element with separator class


How to include website code into iframe via javascript?

I do a curl request with php and the response is a complete website including doctype, html section and so on. Now I want insert this code into an iframe. In my opionion this only can be done with javascript. So I echo the javascript code from my php code. Now I have the problem that the html code contains quotes and line breaks. The quotes are masked by addslashes php function. And I replace the linebreaks with preg_replace php function. But I always get an error "unterminated string literal". You can see the error an this page using for e.g. firebug: http://ift.tt/1aHO9ji The iframe should be shown in the lowermost section called "Hotelbewertungen". Thanks for any suggestion.


PHP received value from JavaScript

I create Modal but I'd like to show count "dukung" from my database. I have a problem because, when I query like this >> "select * from sekolah_dukung where kode='valuefromjavascript'";


this is my quote script



var mycode = kode;
<?php
$data_count = "select count(kode) as countkode from sekolah_dukung where kode='mycode'";
$count = mysql_fetch_object($data_count);
?>
h +=' <b><?php echo $count->countkode ?></b>


this is my full script



<script>
function profile(kode,logo,alamat,ket,nama_sekolah,status_sekolah,orientasi_logo)
{
var ip = '<?php echo $_SERVER['REMOTE_ADDR']; ?>';
var mycode = kode;
var h ='';
h +='<div id="openModal" class="modalDialog" >';
h +='<div style="border:1px solid #369ace;">';
h +=' <a onclick="remDialog()" title="Close" class="close">X</a><br/>';
h +=' <h2 style="border-radius: 25px; border: 2px ; padding: 10px; background-color:#359ace; width: auto;"><center>'+nama_sekolah+'</center></h2>';
h +=' <div id="container2">';
h +=' <div id="container1">';
h +=' <div id="col1">';
h +=' <center><img style=" padding: 5px 30px;" width="160px" height="160px" src="images/sekolah/logo/'+logo+'">';
h +=' <p>Klik Disini untuk mendukung agar sekolah ini menampilkan <br/> brosur online <br/></p>';
h +=' <a href="#" id="dukung" style="cursor:pointer;"><button>Ayo Kami Dukung</button></a><br/>Jumlah yang mendukung <br/>';
<?php
$data_count = "select count(kode) as countkode from sekolah_dukung where kode='mycode'";
$count = mysql_fetch_object($data_count);
?>
h +=' <b><?php echo $count->countkode ?></b></center>';
h +=' </div>';
h +=' <div id="col2"><br/>';
h +=' <p><i class="fa fa-home fa-2x"></i> <font color="black">'+alamat+'</p><br/>';
h +=' <p><i class="fa fa-phone fa-2x"></i> <font color="black">0324242324</p>';
h +=' <br/><br/><br/><b>Keterangan :</b> <br/>'+ket+'';
h +=' </div>';
h +=' </div>';
h +=' </div>';
h +=' </div>';
h +='</div>';
$('body').append(h);
$('#dukung').click(function() {
kirimdukung(mycode,ip);
});
}

function kirimdukung(mycode,ip)
{
$.ajax({
url: 'dukung.php?kode='+mycode+'&ip='+ip,
type: 'GET',
success:function(result){
if (result=="True")
{
alert('Terima Kasih Atas Dukungan Anda');
}
else if (result=="False") {
alert('Anda, Sudah Mendukung Sekolah Ini');
}
}
});
}

function remDialog()
{
$("#openModal").remove();
}
</script>

Uncaught TypeError: string is not a function - on google Chart

Hi i have 2 google chart (1 calendar and the other LineChart) im getting the Uncaught TypeError: string is not a function and Uncaught TypeError: undefined is not a function. Yesterday it worked fine and i could see the two, but today i get this error and i can only display one of the char or the calendar. In separated files i dont get any error, i revised the json and it shows the data i want to retrieve.



<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://ift.tt/JuZcy0"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':["corechart"]});

google.load("visualization", "1.1", {packages:["calendar"]});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawCalendar);


function drawCalendar() {

$.ajax({
url: 'getCalendario.php',
dataType: 'json',
success: function (jsonData) {
var options = {
title: "Calendario",
height: 200,

daysOfWeek: 'LMMJVSD'
};


// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.Calendar(document.getElementById('calendar'));



// Instantiate and draw our chart, passing in some options.

chart.draw(data, options);
}
});
$.ajax({
url: 'getChart.php',
dataType: 'json',
success: function (jsonData) {
// Create our data table out of JSON data loaded from server.
var options = {
title: 'Estado de Bateria',
width: 800,
height: 400,
vAxis: {
minValue: 0,
maxValue: 100,

}

};
var data = new google.visualization.DataTable(jsonData);

// Instantiate and draw our chart, passing in some options.
var chartBat = new google.visualization.LineChart(document.getElementById('battery'));


chartBat.draw(data, options);
}
});
}
</script>
</head>

<body>
<!--Div that will hold the pie chart-->
<div id="calendar" ></div>
<div id="battery"></div>
</body>
</html>

Webpack Uglify causes routing to stop work

When I uglify webpack bundle, routing stops work without any error message or log message. I am using oclazyload to lazy load.


Here is the code in app.route.js



module.exports = function (app) {
var routeConfig = function ($stateProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/dashboard/dashboard.min.html',
title: 'Home',
ncyBreadcrumb: {
label: 'Home'
}
})
.state('organizationStructure', {
url: '/organizationStructure',
templateUrl: 'app/admin/organizationStructure/manageHierarchy/manageHierarchyShell.min.html',
'abstract': true,
ncyBreadcrumb: {
skip: true
},
resolve: ['$q', '$ocLazyLoad', function ($q, $ocLazyLoad) {
var deferred = $q.defer();

require.ensure([], function () {
var mod = require('./organizationStructure.module.js');
$ocLazyLoad.load({
name: 'app.organizationStructure'
});
deferred.resolve(mod.controller);
});

return deferred.promise;
}]
})
.state('organizationStructure.organization', {
url: '/organization',
templateUrl: 'app/admin/organizationStructure/manageHierarchy/organization/index.min.html',
controller: 'ManageOrganization',
controllerAs: 'vm',
title: 'Manage Organization',
ncyBreadcrumb: {
label: 'Manage Organization',
parent: 'home'
}
});
}

app.config(routeConfig);
return routeConfig;


};


Here is the code in app.module.js



var app = angular.module('app', [
'ui.router',
'restangular',
'ui.bootstrap',
'ncy-angular-breadcrumb',
'oc.lazyLoad'


]);


//Base Route require('./app.route.js')(app);


When I minify the bundle, app routing stops working. Otherwise it works fine. Please provide me a solution. Also I am using ngAnnotate. Dependencies are injected safely in minified file.


Can't use javascript within jpanelmenu

I'm trying to use this autocomplete search:



<script type="text/javascript">

jQuery(function() {
var availableTags = [
"Comedy",
"Music",
"Radio"
];
jQuery( "#tags" ).autocomplete({
source: availableTags
});
});

</script>


Inside this script:



/**
*
* jPanelMenu 1.4.1 (http://jpanelmenu.com)
* By Anthony Colangelo (http://acolangelo.com)
*
* */

(function($){
$.jPanelMenu = function(options) {
if ( typeof(options) == "undefined" || options == null ) { options = {}; };

var jP = {
options: $.extend({
menu: '#menu',
panel: 'body',
trigger: '.menu-trigger',
excludedPanelContent: 'style, script',
clone: true,
keepEventHandlers: false,

direction: 'left',
openPosition: '250px',
animated: true,
closeOnContentClick: true,

keyboardShortcuts: [
{
code: 27,
open: false,
close: true
},
{
code: 37,
open: false,
close: true
},
{
code: 39,
open: true,
close: true
},
{
code: 77,
open: true,
close: true
}
],

duration: 150,
openDuration: options.duration || 150,
closeDuration: options.duration || 150,

easing: 'ease-in-out',
openEasing: options.easing || 'ease-in-out',
closeEasing: options.easing || 'ease-in-out',

before: function(){ },
beforeOpen: function(){ },
beforeClose: function(){ },

after: function(){ },
afterOpen: function(){ },
afterClose: function(){ },

beforeOn: function(){ },
afterOn: function(){ },

beforeOff: function(){ },
afterOff: function(){ }
},options),

settings: {
transitionsSupported: 'WebkitTransition' in document.body.style ||
'MozTransition' in document.body.style ||
'msTransition' in document.body.style ||
'OTransition' in document.body.style ||
'Transition' in document.body.style
,
transformsSupported: 'WebkitTransform' in document.body.style ||
'MozTransform' in document.body.style ||
'msTransform' in document.body.style ||
'OTransform' in document.body.style ||
'Transform' in document.body.style
,
cssPrefix: '',
panelPosition: 'static',
positionUnits: 'px'
},

menu: '#jPanelMenu-menu',

panel: '.jPanelMenu-panel',

timeouts: {},

clearTimeouts: function() {
clearTimeout(jP.timeouts.open);
clearTimeout(jP.timeouts.afterOpen);
clearTimeout(jP.timeouts.afterClose);
},

setPositionUnits: function() {
var foundUnit = false,
allowedUnits = ['%','px','em']
;

for (var unitID = 0; unitID < allowedUnits.length; unitID++) {
var unit = allowedUnits[unitID];
if ( jP.options.openPosition.toString().substr(-unit.length) == unit )
{
foundUnit = true;
jP.settings.positionUnits = unit;
}
}

if ( !foundUnit ) { jP.options.openPosition = parseInt(jP.options.openPosition) + jP.settings.positionUnits }
},

computePositionStyle: function(open, string) {
var position = (open)?jP.options.openPosition:'0' + jP.settings.positionUnits;
var property = {};
if ( jP.settings.transformsSupported ) {
var direction = (open && jP.options.direction == 'right')?'-':'';
var translate = 'translate3d(' + direction + position + ',0,0)';
var transform = 'transform';

if ( string ) {
property = '';
if ( jP.settings.cssPrefix != '' ) { property = jP.settings.cssPrefix + transform + ':' + translate + ';' }
property += transform + ':' + translate + ';';
} else {
if ( jP.settings.cssPrefix != '' ) { property[jP.settings.cssPrefix + transform] = translate; }
property[transform] = translate;
}
} else {
if ( string ) {
property = '';
property = jP.options.direction + ': ' + position + ';';
} else {
property[jP.options.direction] = position;
}
}
return property;
},

setCSSPrefix: function() {
jP.settings.cssPrefix = jP.getCSSPrefix();
},

setjPanelMenuStyles: function() {
var bg = 'background:#fff',
htmlBG = $('html').css('background-color'),
bodyBG = $('body').css('background-color');

var backgroundGenerator = function(element){
var bgs = [];
$.each(['background-color','background-image','background-position','background-repeat','background-attachment','background-size','background-clip'], function(i,value){
if( element.css(value) !== '' ) {
bgs.push(value+':'+element.css(value));
}
});
return bgs.join(';');
};

if ( bodyBG !== 'transparent' && bodyBG !== "rgba(0, 0, 0, 0)") {
bg = backgroundGenerator($('body'));
} else if ( htmlBG !== 'transparent' && htmlBG !== "rgba(0, 0, 0, 0)") {
bg = backgroundGenerator($('html'));
}

if ( $('#jPanelMenu-style-master').length == 0 ) {
$('body').append('<style id="jPanelMenu-style-master">body{width:100%}.jPanelMenu,body{overflow-x:hidden}#jPanelMenu-menu{display:block;position:fixed;top:0;'+jP.options.direction+':0;height:100%;z-index:-1;overflow-x:hidden;overflow-y:scroll;-webkit-overflow-scrolling:touch}.jPanelMenu-panel{position:static;'+jP.options.direction+':0;top:0;z-index:2;width:100%;min-height:100%;' + bg + ';}</style>');
}
},

setMenuState: function(open) {
var position = (open)?'open':'closed';
$(jP.options.panel).attr('data-menu-position', position);
},

getMenuState: function() {
return $(jP.options.panel).attr('data-menu-position');
},

menuIsOpen: function() {
if ( jP.getMenuState() == 'open' ) return true;
else return false;
},

setMenuStyle: function(styles) {
$(jP.menu).css(styles);
},

setPanelStyle: function(styles) {
$(jP.panel).css(styles);
},

showMenu: function() {
jP.setMenuStyle({
display: 'block'
});
jP.setMenuStyle({
'z-index': '1'
});
},

hideMenu: function() {
jP.setMenuStyle({
'z-index': '-1'
});
jP.setMenuStyle({
display: 'none'
});
},

enableTransitions: function(duration, easing) {
var formattedDuration = duration/1000;
var formattedEasing = jP.getCSSEasingFunction(easing);
jP.disableTransitions();
$('body').append('<style id="jPanelMenu-style-transitions">.jPanelMenu-panel{' + jP.settings.cssPrefix + 'transition: all ' + formattedDuration + 's ' + formattedEasing + '; transition: all ' + formattedDuration + 's ' + formattedEasing + ';}</style>');
},

disableTransitions: function() {
$('#jPanelMenu-style-transitions').remove();
},

getCSSEasingFunction: function(name) {
switch ( name )
{
case 'linear':
return name;
break;

case 'ease':
return name;
break;

case 'ease-in':
return name;
break;

case 'ease-out':
return name;
break;

case 'ease-in-out':
return name;
break;

default:
return 'ease-in-out';
break;
}
},

getJSEasingFunction: function(name) {
switch ( name )
{
case 'linear':
return name;
break;

default:
return 'swing';
break;
}
},

getVendorPrefix: function() {
// Thanks to Lea Verou for this beautiful function. (http://ift.tt/1O4znoZ)
if('result' in arguments.callee) return arguments.callee.result;

var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/;

var someScript = document.getElementsByTagName('script')[0];

for(var prop in someScript.style)
{
if(regex.test(prop))
{
// test is faster than match, so it's better to perform
// that on the lot and match only when necessary
return arguments.callee.result = prop.match(regex)[0];
}

}

// Nothing found so far? Webkit does not enumerate over the CSS properties of the style object.
// However (prop in style) returns the correct value, so we'll have to test for
// the precence of a specific property
if('WebkitOpacity' in someScript.style) return arguments.callee.result = 'Webkit';
if('KhtmlOpacity' in someScript.style) return arguments.callee.result = 'Khtml';

return arguments.callee.result = '';
},

getCSSPrefix: function() {
var prefix = jP.getVendorPrefix();
if ( prefix != '' ) { return '-' + prefix.toLowerCase() + '-'; }
return '';
},

openMenu: function(animated) {
if ( typeof(animated) == "undefined" || animated == null ) { animated = jP.options.animated };

jP.clearTimeouts();

jP.options.before();
jP.options.beforeOpen();

jP.setMenuState(true);

jP.showMenu();

var animationChecks = {
none: (!animated)?true:false,
transitions: (animated && jP.settings.transitionsSupported)?true:false
};

if ( animationChecks.transitions || animationChecks.none ) {
if ( animationChecks.none ) jP.disableTransitions();
if ( animationChecks.transitions ) jP.enableTransitions(jP.options.openDuration, jP.options.openEasing);

var newPanelStyle = jP.computePositionStyle(true);
jP.setPanelStyle(newPanelStyle);

jP.timeouts.afterOpen = setTimeout(function(){
jP.options.after();
jP.options.afterOpen();
jP.initiateContentClickListeners();
}, jP.options.openDuration);
}
else {
var formattedEasing = jP.getJSEasingFunction(jP.options.openEasing);

var animationOptions = {};
animationOptions[jP.options.direction] = jP.options.openPosition;
$(jP.panel).stop().animate(animationOptions, jP.options.openDuration, formattedEasing, function(){
jP.options.after();
jP.options.afterOpen();
jP.initiateContentClickListeners();
});
}
},

closeMenu: function(animated) {
if ( typeof(animated) == "undefined" || animated == null ) { animated = jP.options.animated };

jP.clearTimeouts();

jP.options.before();
jP.options.beforeClose();

jP.setMenuState(false);

var animationChecks = {
none: (!animated)?true:false,
transitions: (animated && jP.settings.transitionsSupported)?true:false
};

if ( animationChecks.transitions || animationChecks.none ) {
if ( animationChecks.none ) jP.disableTransitions();
if ( animationChecks.transitions ) jP.enableTransitions(jP.options.closeDuration, jP.options.closeEasing);

var newPanelStyle = jP.computePositionStyle();
jP.setPanelStyle(newPanelStyle);

jP.timeouts.afterClose = setTimeout(function(){
jP.disableTransitions();

jP.hideMenu();
jP.options.after();
jP.options.afterClose();
jP.destroyContentClickListeners();
}, jP.options.closeDuration);
}
else {
var formattedEasing = jP.getJSEasingFunction(jP.options.closeEasing);

var animationOptions = {};
animationOptions[jP.options.direction] = 0 + jP.settings.positionUnits;
$(jP.panel).stop().animate(animationOptions, jP.options.closeDuration, formattedEasing, function(){
jP.hideMenu();
jP.options.after();
jP.options.afterClose();
jP.destroyContentClickListeners();
});
}
},

triggerMenu: function(animated) {
if ( jP.menuIsOpen() ) jP.closeMenu(animated);
else jP.openMenu(animated);
},

initiateClickListeners: function() {
$(document).on('click touchend',jP.options.trigger,function(e){
jP.triggerMenu(jP.options.animated); e.preventDefault();
});
},

destroyClickListeners: function() {
$(document).off('click touchend',jP.options.trigger,null);
},

initiateContentClickListeners: function() {
if ( !jP.options.closeOnContentClick ) return false;

$(document).on('click touchend',jP.panel,function(e){
if ( jP.menuIsOpen() ) jP.closeMenu(jP.options.animated);
e.preventDefault();
});
},

destroyContentClickListeners: function() {
if ( !jP.options.closeOnContentClick ) return false;

$(document).off('click touchend',jP.panel,null);
},

initiateKeyboardListeners: function() {
var preventKeyListeners = ['input', 'textarea', 'select'];
$(document).on('keydown',function(e){
var target = $(e.target),
prevent = false;

$.each(preventKeyListeners, function(){
if (target.is(this.toString())) {
prevent = true;
}
});

if ( prevent ) return true;

for ( mapping in jP.options.keyboardShortcuts ) {
if ( e.which == jP.options.keyboardShortcuts[mapping].code ) {
var key = jP.options.keyboardShortcuts[mapping];

if ( key.open && key.close ) { jP.triggerMenu(jP.options.animated); }
else if ( (key.open && !key.close) && !jP.menuIsOpen() ) { jP.openMenu(jP.options.animated); }
else if ( (!key.open && key.close) && jP.menuIsOpen() ) { jP.closeMenu(jP.options.animated); }

e.preventDefault();
}
}
});
},

destroyKeyboardListeners: function() {
$(document).off('keydown',null);
},

setupMarkup: function() {
$('html').addClass('jPanelMenu');
$(jP.options.panel + ' > *').not(jP.menu + ', ' + jP.options.excludedPanelContent).wrapAll('<div class="' + jP.panel.replace('.','') + '"/>');
var menu = ( jP.options.clone )?$(jP.options.menu).clone(jP.options.keepEventHandlers):$(jP.options.menu);
menu.attr('id', jP.menu.replace('#','')).insertAfter(jP.options.panel + ' > ' + jP.panel);
},

resetMarkup: function() {
$('html').removeClass('jPanelMenu');
$(jP.options.panel + ' > ' + jP.panel + ' > *').unwrap();
$(jP.menu).remove();
},

init: function() {
jP.options.beforeOn();

jP.setPositionUnits();
jP.setCSSPrefix();
jP.initiateClickListeners();
if ( Object.prototype.toString.call(jP.options.keyboardShortcuts) === '[object Array]' ) { jP.initiateKeyboardListeners(); }

jP.setjPanelMenuStyles();
jP.setMenuState(false);
jP.setupMarkup();

jP.setPanelStyle({ position: (( jP.options.animated && jP.settings.panelPosition === 'static' )?'relative':jP.settings.panelPosition) });
jP.setMenuStyle({ width: jP.options.openPosition });

jP.closeMenu(false);

jP.options.afterOn();
},

destroy: function() {
jP.options.beforeOff();

jP.closeMenu();
jP.destroyClickListeners();
if ( Object.prototype.toString.call(jP.options.keyboardShortcuts) === '[object Array]' ) { jP.destroyKeyboardListeners(); }

jP.resetMarkup();
var childrenStyles = {};
childrenStyles[jP.options.direction] = 'auto';

jP.options.afterOff();
}
};

return {
on: jP.init,
off: jP.destroy,
trigger: jP.triggerMenu,
open: jP.openMenu,
close: jP.closeMenu,
isOpen: jP.menuIsOpen,
menu: jP.menu,
getMenu: function() { return $(jP.menu); },
panel: jP.panel,
getPanel: function() { return $(jP.panel); },
setPosition: function(position) {
if ( typeof(position) == "undefined" || position == null ) {
position = jP.options.openPosition
}
jP.options.openPosition = position;
jP.setMenuStyle({ width: jP.options.openPosition });
}
};
};
})(jQuery);

</script>

<script type="text/javascript">

jQuery(function() {
var jPM = jQuery.jPanelMenu();
var jPM = jQuery.jPanelMenu({
menu: '#menu-selector',
trigger: '.menu-trigger-selector',
duration: 300
});
jPM.on();
})

</script>


The HTML looks like



<div class="menu-trigger-selector"><img src="http://ift.tt/1JV7ytJ" alt="Menu Button" title="Menu Button"></div>
<div id="menu-selector" style="display:none;">

<ul class="info">
<li id="about" class="noselect"><a href="#">Home</a></li>
<li id="faq" class="noselect"><a href="#">About</a></li>
<li id="contribute" class="noselect"><a href="#">Contact</a></li>
</ul>

<ul class="login-register">
<li id="login" class="noselect"><a href="#">Login</a></li>
<li id="register" class="noselect"><a href="#">Register</a></li>
</ul>

<div class="ui-widget">
<input id="tags" placeholder="Search"></input>
</div>

<ul class="podcast-list">
<li>Main1
<ul class="podcasts">
<li>Sub</li>
<li>Sub</li>
<li>Sub</li>
<li>Sub</li>
</ul>
</li>

</ul>

</div>

<div class="container">
...
</div>


Loading resources in this order



<script src="http://ift.tt/1yCEpkO"></script>
<script src="../jquery.once.js?v=1.2"></script>
<script src="../drupal.js?nmk3bg"></script>
<script src="http://ift.tt/1DG5WSS"></script>
<link rel="stylesheet" href="http://ift.tt/1BoDuVn" />
<link href='http://ift.tt/19nU1g7' rel='stylesheet' type='text/css'>
<script src="http://ift.tt/IWF2gG"></script>


No jquery works at all though. Scripts work fine anywhere in the body, but not inside the side menu. There are no console errors. I've tried 2 other side menus but javascript doesn't work within them either. I need help either fixing this one or finding another one that supports javascript.


How to fix ReferenceError: Can't find variable: jQuery/$

I know, there are a lot of questions like this, but they doesn't help me.


My situation is following.



  1. I copy one (working) site with some changes to create another.

  2. After I did it with not so much changes javascript on new site doesn't work, saying "ReferenceError: Can't find variable: jQuery" and "ReferenceError: Can't find variable: $".


  3. I added into the code alerts:



    alert('aaa');
    var x=$('td[type="x"]').size();
    alert('aaa1');



and see "aaa" alert, but don't see "aaa".




  1. I've checked, like it is said here, with Safari's debugger that jquery files are found and loaded, I can see them in "Resources" tab.




  2. adding ready in the line doesn't help:



    alert('aaa');
    var x=$(document).ready($('td[type="x"]').size());
    alert('aaa1');



    1. I belive the jquery was included before using it, my code looks like this:







<... HTML>
<script src="{$JS_DIR}/jquery/jquery-ui-1.8.6.custom.min.js?{$JS_VERSION}" language="javascript" type="text/javascript"></script>
<... OTHER JS includes>
{literal}
<script type="text/javascript">
<... other functions>

function XX() {
alert('aaa');
var X=$(document).ready($('td[type="x"]').size());
alert('aaa1');
<... other functions>
</script>
{/literal}
<EOF>



What else I can do about it?


I have OSX 10.10.3 and Safari 8.0.5.


How to set baseurl correctly in Android WebView?

I am using WebView to display some html content from web (using loadDataWithBaseUrl() method). The html data could be any html content, simple plain text or rich html with img tags. I inject some JavaScript also in WebView which sets some style and does html manipulation. Now the problem is that sometimes JavaScript does not load in the WebView. It happens when the html data contains some images. Also, sometimes images in the html does not load. I tried setting a dummy baseurl (http://dummy.baseurl) in loadDataWithBaseUrl() which solves the JavaScript loading issue. But the image loading issue is still remains.


Am I setting the baseurl correctly? Is there any other baseurl I can set which will help?


Cannot Read Property 'top' occurs when click button to open modal window

The following code works when the page loads. However when I click on a button that is supposed to open a modal window I get the following error:


Uncaught TypeError: Cannot read property 'top' of undefined


How can I fix this error?



if ($(window).width() > 992) {

(function($) {
"use strict";
$(".page-scroll a[href^='#'], #intro a").on('click', function(e) {
e.preventDefault();
var hash = this.hash;
$('html, body').stop().animate({
scrollTop: $(hash).offset().top - 100}, 2000, 'easeOutExpo');
});
})(jQuery);

$('body').scrollspy({
target: '.navbar',
offset: 110
});
// alert("large");
}
else {

(function($) {
"use strict";
$(".page-scroll a[href^='#'], #intro a").on('click', function(e) {
e.preventDefault();
var hash = this.hash;
$('html, body').stop().animate({
scrollTop: $(hash).offset().top - 50}, 2000, 'easeOutExpo');
});
})(jQuery);

$('body').scrollspy({
target: '.navbar',
offset: 70
});
// alert("small");
}

//modal popup function
function popup_modal(item){
var link = $(item).attr('id');
$('#bootstrap_modal').load('/'+link+'');
$('#bootstrap_modal').modal('show');
$("#bootstrap_modal").on("show", function () {
$("body").addClass("modal-open");
}).on("hidden", function () {
$("body").removeClass("modal-open")
});
}

//Modal pop up
$('.mmodal').on('click', function(){
popup_modal(this);
});

Creating basic javascript library structure [on hold]

I'm interested in creating a basic javascript library structure ( structure because a library is a broad subject ). I looked at the jquery code for inspiration but there are things I don't understand.


Here is an example of what I don't understand:



(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ){ ... }


Question:


What is happening in the code above? And is this needed to create the structure of a javascript library?


Thank you.


i don't know i saw it in every js lib!


Limiting an element from appearing out of the screen

I'm trying to make a square appear at random positions of the screen. I have set it's position property to be absolute and in javascript i'm running a random number between 0 to 100, this will then be assigned as a percentage to top and left property. however if the random number was ~100 or a bit less the square will appear out of the screen. How do I fix this problem?



var shape1 = document.getElementById("shape1");

//creating random number to 100
function randomNum() {
var r = Math.random();
var y = (r * (100 - 0 + 1)) + 0;
var x = Math.floor(y);
console.log(x);
return x;
}
//reappear at random position
function reappear(object) {
object.style.left = randomNum().toString() + "%";
object.style.top = randomNum().toString() + "%";
object.style.display = "block";
}

reappear(shape1);


code: http://ift.tt/1H1C5Yh


How do you check if the data is null in http.get in angularjs AND do something?

My code:



<script>
function customersController($scope, $http) {
$http.get("http://ift.tt/1b8ep6U")
.success(function (response) { $scope.names = response; });
}
</script>

<table class="plansbox" cellspacing="0" rules="all" id="ctl00_ContentPlaceHolder1_FULLTALKTIME" style="border-width:0px;width:100%;border-collapse:collapse;">
<tbody><tr class="rechargeplansheader">
<th scope="col">AMOUNT</th><th scope="col">TALKTIME</th><th scope="col">VALIDITY</th><th scope="col">DESCRIPTION</th>
</tr><tr class="GridRow" ng-repeat="x in names | filter: { plantype: 'TopUp' }" onclick="label1('220');" style="font-family:Verdana;cursor: pointer; cursor: hand;">
<td style="width:10%;">

<span id="ctl00_ContentPlaceHolder1_FULLTALKTIME_ctl02_lblAmount" style="font-weight:bold;">{{ x.Amount }}</span>
</td><td style="width:10%;">
<span id="ctl00_ContentPlaceHolder1_FULLTALKTIME_ctl02_lbltalktime" style="font-weight:bold;">{{x.Talktime }}</span>
</td><td style="width:10%;">
<span id="ctl00_ContentPlaceHolder1_FULLTALKTIME_ctl02_lblvalidity" style="font-weight:bold;">{{ x.Validity }}</span>
</td><td style="width:70%;">
<span id="ctl00_ContentPlaceHolder1_FULLTALKTIME_ctl02_lbldescription">{{ x.Description}}</span>
</td>
</tr>
</tbody></table>


As you can see I am able to get the data, check if the returned data is null, but do to show another div in the null case.


Please help me I am new to angularjs.


AngularJS form and null/empty values

I am working with a somewhat dynamic AngularJS form. In other words, I am able to add rows of input fields, etc. So my approach was to start with a $scope.formData empty object, to encapsulate all the properties that are bound to both static and dynamic HTML form elements.


The AngularJS code is as follows:



(function() {
var formApp = angular.module("formApp", []);
formApp.controller("FormCtrl", function ($scope, $timeout) {
$scope.formData = {};
$scope.formData.subscribers = [
{ name: null, email: null }
];
$scope.addSubscriber = function() {
$scope.formData.subscribers.push({ name: null, email: null });
};
});
})();


The HTML for the AngularJS form:



<body data-ng-app="formApp">
<div data-ng-controller="FormCtrl">
<p>
Name of Topic: <input type="text" data-ng-model="formData.title" placeholder="enter a title" />
</p>
Subscribers:
<button data-ng-click="addSubscriber()">Add subscriber</button>
<table>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tr data-ng-repeat="subscriber in formData.subscribers">
<td><input type="text" data-ng-model="subscriber.name" placeholder="enter name" /></td>
<td><input type="text" data-ng-model="subscriber.email" placeholder="enter email" /></td>
</tr>
</table>
<hr style="margin:1em 0;" />
<p>
<em>Debug info</em>: {{ formData }}
</p>
</div>
</body>


Note the Debug info section at the end, which displays the $scope.formData object and its contents. I have a couple of issues with the way I have implemented this form.



  • When the page first loads, there is no formData.title property in the $scope, but since it is bound to the Title input text field, when I start typing a value, the title property gets added to the $scope. However when I delete the value in the input text field, the formData.title property still exists in the $scope as an empty string. I suppose this is okay, but I really want to clean up empty or null values when submitting the form. I would like to do it on the client side if it is easy to do so, so the server side code does not have to clean up anything.

  • With the dynamic Subscribers section, I can keep adding as many rows as I want, but ultimately, I would like to filter out all empty subscriber objects on the client side.


Does AngularJS have any options for detecting and cleaning null/empty values in the $scope before further processing, such as a $http POST?


Note I have set up a jsFiddle for this example.


Socket.io not recognizing event inside Leap.loop

I am working on making an interface for a Leap motion controlled robot. From the server side node.js, I am emitting an event 'action' which contains the data to be displayed on a HTML page. I have implemented a modified version of the leap rigged hand (original code: http://ift.tt/1HGVe0V).



<html>
<head>
<title>Locomotion</title>
<script src="http://ift.tt/1JVcsqq"></script>
<script src="http://ift.tt/1HGVfSq"></script>
<script src="http://ift.tt/1JVcq1X"></script>
<script src="http://ift.tt/1HGVe0X"></script>
<script src="jquery.js"></script>
<script src="/http://ift.tt/1aeIZU4"></script>

<style>
body {
font-family: 'Myriad Pro', Helvetica, Arial, 'Lucida Grande', sans-serif;
font-size: 24pt;
color: white;
background-color: #348cb2;
}

#display {
position: fixed;
height: 50px;
width: 300px;
background: #fdd;
bottom: 10;
left: 10;
padding: 5px;
}
#direction {
color: #f77;
display: block;
height: 100%;
width: 200px;
padding-top: 5px;
margin: 0 auto;
text-align: center;
}
</style>
</head>

<body>
<div id="display"><span id="direction">undefined</span></div>
</body>

<script type="text/javascript">
var riggedHandPlugin,
socket = io();
socket.on('action', function(data) {
$('#display').html(data);
});
/*
Leap.loop({
hand: function(hand){
var handMesh = hand.data('riggedHand.mesh');
handMesh.material.opacity = 1;
handMesh.material.color.set('#7b4b2a');
handMesh.material.ambient = handMesh.material.color;
var screenPosition = handMesh.screenPosition(
hand.palmPosition,
riggedHandPlugin.camera
);
}
})
.use('riggedHand', {
scale: 1.5,
opacity : 1
});

riggedHandPlugin = Leap.loopController.plugins.riggedHand; */
</script>


With the above commented version, socket displays the 'action' data. However, the leap rigged hand won't be displayed.


Whereas, uncommenting would show the leap rigged hand, but wouldn't change the 'action' data in the


I'm stuck with this for a couple of days and I can't think of what to do.


Kindly help


Refresh SESSION after change it by submit form

I have code that get me country flag for user when select country from drop down menu like this



define('WCDP_PATH_INCLUDES', dirname(__FILE__) . '/inc');

if (!class_exists('GeoIP')) {
include(WCDP_PATH_INCLUDES . "/geoip.inc");
}
$geo_data = geoip_open(WCDP_PATH_INCLUDES . "/GeoIP.dat", GEOIP_STANDARD);

$country_code = geoip_country_code_by_addr($geo_data, $_SERVER['REMOTE_ADDR']);

$countrynameselect = $_SESSION['countryname'];
if ($countrynameselect){
$country_code = $countrynameselect;
} else {
$country_code = geoip_country_code_by_addr($geo_data, $_SERVER['REMOTE_ADDR']);
}
// Build HTML for flag icons.
?>

<img src="<? bloginfo('stylesheet_directory')?>/flags/sm/<?php echo strtolower($country_code).'.png'; ?>" border="0" style="margin-top:10px" id="flagc" />


Now when user select country from drop down menu, i save country post in SESSION, But when user change agin, itsh not update SESSION, and to update it, we must refresh page to shpw new SESSION value.


What can i do ??


PHP Google Places to find the custom location like Zomato

As in Zomato.com, the website get the location of the user and then shows results (list of restaurants) near it using Google Places.


Can we add some custom locations in Google Places. Fetch the User location and show him our 5 locations(that we added) nearby him in PHP?


Zomato location based search


Lazyload an entire Bootstrap carousel

Long time reader, first time poster.


I have recently started learning to use bootstrap.


I am stuck trying to get the a Bootstrap carousel to lazyload (or similar effect).


I have pieced together the effect I'm going for, my first four images 'flick through' and the carrousel stops on my final image – but what I can't manage is to have the entire carousel lazyload before the carousel starts.


I've looked at lazysizes (by aFarkas on Github) – but I can't [even] make this work.


This is my work in progress – http://ift.tt/1DSImmJ – I'd like the carousel to show a 'load in progress' before it starts, like it does at this http://ift.tt/1OT63Pe as an example.


As is often the case when I'm learning my way around these things, I think it might be that I am missing something simple – is this the case?


gulp-recursive-concat with slashes on windows?

I have an issue with gulp-recursive-concat. Everything worked until today.


Here is the task :



gulp.task ('concatenate', function ()
{
return gulp.src ('./public/js_dev/**/*.js')
.pipe (recursiveConcat ({dist: './public/js/', extname: ".js"}))
.pipe (stripDebug ())
.pipe (uglify ())
.pipe (gulp.dest ('./public/js/'));
});


When I open utils.js used by gulp-recursice-concat, a test based on a regexp is made :



var arrayFolders = (base + dirname).match(/[a-zA-Z0-9_-]+\/+/gi),
folderName = arrayFolders[arrayFolders.length -1];
folderName = folderName.replace("/", "");


But the problem is (base + dirname) doesn't contain any slashes but only backslashes, so the program crashes on the next line because arrayFolders is null.


Why the package has suddently stopped working ? I tried to remove and install it again with no success.


How to update elements that are bound to functions with Angular?

What is the correct way to do have elements update regularly, without explicitly doing that for each variable in an $interval callback?


This would be useful in the following situation: an element's content is bound to a function, like this:



<p ng-bind="timeLeft()"></p>


The timeleft() function returns a value depending on the current time. It needs to be refreshed every 20 ms.


I've tried the following, which works:



$scope.updateView = function(){
if(!$scope.$$phase) { // To prevent this: "Error: [$rootScope:inprog] $digest already in progress"
$scope.apply();
}
}
$interval( function(){
$scope.updateView();
}, 50);


I noticed just using $interval may already suffice, in my setup this works too:



$scope.updateView = function(){
}
$interval( function(){
$scope.updateView();
}, 20);


Would it be reliable to use that last solution?


Is there anyway to fix `Object.create` side effects in Chrome?

I was playing around today when I noticed that some of my objects in Chrome's console were being displayed as Object instead of the constructor function name.


This was odd, so I boiled it down to the following code:



function Baz() {
this.baz = true;
}
var b = new Baz();
var c = Object.create(b);
console.log(b);


This has to be a Chrome bug right? Is there anyway to get Chrome to correctly report Baz here?


This is important for debugging purposes.


Missing formal parameter javascript

I am making an object. I have to assign key and value from html fields. But when I am doing that. It is giving an error "missing formal parameter". fiddle



<span class="value">
<input type="checkbox" name="slt" value="1">
<input type="checkbox" name="slt" value="0" checked="checked">
</span>


<select class="key">
<option value="1">one</option>
</select>


var a= {$('[name="slt"]:checked').val():$('.key').val()}
console.log(a)

Javascript not waiting for ajax with bootstrap-wizard.js

I have a bootstrap-wizard as follows:



<div class="wizard-card" data-cardname="credential">
<h3>Credential</h3>
<div class="wizard-input-section">
<p>Username</p>
<div class="form-group">
<div class="col-sm-6">
<input type="text" class="form-control" id="Busername" name="Busername" placeholder="Username" required data-parsley-type="alphanum" data-validate="checkNameAvailable" data-msg="Alphanumeric allowed only" />
</div>
</div>
<p>Password</p>
<div class="form-group">
<div class="col-sm-6">
<input type="password" class="form-control" id="Bpassword" name="Bpassword" placeholder="Password" />
</div>
</div>
<p>Re-type Password</p>
<div class="form-group">
<div class="col-sm-6">
<input type="password" class="form-control" id="Bpassowrd2" name="Bpassword2" placeholder="Retype Password"/>
</div>
</div>
</div>
</div>


The input <input type="text" class="form-control" id="Busername" name="Busername" placeholder="Username" required data-parsley-type="alphanum" data-validate="checkNameAvailable" data-msg="Alphanumeric allowed only" /> calls the checkNameAvailable function to make validation.


checkNameAvailable function: Which makes an ajax call to check if the name is available or not.



function checkNameAvailable(el){
if($("#"+$(el).attr('id')).parsley().isValid()){
var data = $(el).val();
if($(el).attr('id') == "Busername"){
var type = "B";
}else{
var type = "I";
}
$.ajax({
method: "POST",
url: "isUserAvailableCommon",
async: false,
data: {Busername: data, _token: $("#_token").val(), _type: type },
success: function(msg) {
var retValue = {};
if(msg == "OK"){
retValue.status = true;
console.log(retValue);
return retValue;
}else{
retValue.status = false;
console.log(retValue);
return retValue;
}
}

});
}
}


The problem is that the variable retValue is not returned to the bootstrap-wizard validation.


However if i try like this it works but not when implementing with ajax



function checkNameAvailable(el){
var retValue = {};
retValue.status = false;
return retValue;
}


Any idea how to make it work with ajax? I have tried callbacks and methods described in Javascript function not waiting for AJAX responsebut it is still not working.


Opening webpage in javascript on trigger

I'm using a script called "HIT Scraper WITH EXPORT" to help me with my job. Right now it's set up in a way that any time there is a new posting the page plays a audible sound/ding. Normally when this happens I have to switch tabs and manually click on the new listing to preview it. I'm trying to make it so it automatically opens the listing before/after dinging. Also if possible having it put focus on that tab if I'm in a different one. Is any of this possible, where should I start? I'll post the code and some areas of interest I noticed, I just don't know what to do with these areas.. Thank you in advance.


The function that runs when a new hit is found I think:



function newHits(dingNoise) {
//console.log(dingNoise);
if (dingNoise || newHitDing)
document.getElementById("ding_noise"+audio_index).play();
}


I think "preview_link" is the var I need to automatically open after the ding sound plays.



var preview_link = "/mturk/preview?groupId=" + group_ID;


So my logic was something like:



function newHits(dingNoise) {
//console.log(dingNoise);
if (dingNoise || newHitDing)
document.getElementById("ding_noise"+audio_index).play();
window.open("/mturk/preview?groupId=") + group_ID;

}


Which did not work.. Here's the full script if anyone has any ideas.. Thanks again.


http://ift.tt/1HGVfBY


Blogger URL PARAMETER javascript

I have a blog in blogger platform.


I need some extra URL parameter to add in my blog and it post. If I like to keep ?id=100 or ?id=parameter after all original link


Like if some of visit my blog.



http://ift.tt/1Ip51Xr
http://ift.tt/1O2Oob4


If someone Open blogger Post



http://ift.tt/1Ip51Xt
http://ift.tt/1O2Oob9


If some of Open pages.



http://ift.tt/1Ip54T2
http://ift.tt/1O2OoYD


Hope you understand, i just like to keep some extra ?id=anything after all original link.


Please tell me the javascript which redirect to ?something=something after original link.


Does modelObject.save() only update an existing database document when the modelObject was obtained from the database itself?

To use an example that demonstrates the question, assume I have a User model defined by the following schema:



var UserSchema = new Schema({
username: String,
email: String
}
mongoose.model('User', UserSchema);


I know that to update a user using the save method, I could query the user and then save changes like so:



User.findOne({username: usernameTofind}, function(err, user) {
//ignore errors for brevity
user.email = newEmail;
user.save(function(err) { console.log('User email updated') });
});


But if I try to create a new User object with the exact same field values (including the _id) is there any possibility of overwriting the database document? I would assume not, because in theory this would mean that a malicious user could exploit an insecure api and overwrite existing documents (for instance using a 'Create a New Account' request, which wouldn't/couldn't rely on the user already being authenticated) , but more importantly, when I try to do this using a request tool (I'm using Postman, but I'm sure a similar curl command would suffice), I get a duplicate _id error



MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index


So I just want to clarify that the only way to update an existing document is to query for the document, modify the returned instance, then call the save method on that instance, OR use the static update(). Both of these could be secured by requiring authentication.


If it helps, my motivation for this question is mentioned above, in that I want to make sure a user is not able to overwrite an existing document if a method such as the following is exposed publicly:



userCtrl.create = function(req, res, next) {
var user = new User(req.body);

user.save(function(err) {
if (err) {
return next(err);
} else {
res.json(user);
}
});
};


Quick Edit: I just realized, if this is the case, then how does the database know the difference between the queried instance and a new User object with the exact same keys and properties?


How to specify Array like class in JSDocs

I have a class which is in some ways is like an array.


First there is a generic part that can be accessed with dot notation like:


myclass.customerlist


myclass.clientlist


myclass.some_dynamic_list_i_added_on_the_fly


i.e. there are generic properties of type Array, maybe documented like this: {Object.}


But also like an array it has certain specific methods


/** * @param {string} name */ myclass.loaddata(name)


loaddata would be a member of myclass and have a string param


I can't see how to specify a class that has known members and also some generic properties that may have any name but are always of a specific type.


google map radar search not giving me place name while printing

I am working on project in which i need place name and place id as output,but i am getting place id correctly but place name it is showing undefined. here is my code thanks in advance.



<html>
<head>
<meta charset="utf-8">
<title>Search for up to 200 places with Radar Search</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="http://ift.tt/1baWrRg"></script>
<script>
var map;
var infoWindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(19.12455, 72.929158),
zoom: 11,
styles: [
{
stylers: [
{ visibility: 'simplified' }
]
},
{
elementType: 'labels',
stylers: [
{ visibility: 'on' }
]
}
]
});
infoWindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
name:'swimming pool'
};
service.radarSearch(request, callback);
}


function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var data;
var count = 1;
var placeIDs = [];
var placeName = [];
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
placeIDs[i] = results[i].place_id;
placeName[i] = results[i].name;
count += 1;
data += "Number : " + count + " The name is :" + placeName[i] + " Id is : " + placeIDs[i] + "<br>";
}
document.getElementById('place_id').innerHTML = data;
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(place, function(result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
infoWindow.setContent('<strong>' + result.name +'</strong>'+ '<br>' + "placeId : " + result.place_id);
infoWindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<h4 id="place_id"></h4>
</body>
</html>


it will print output on screen only it is showing name as undefined.