Underscore - Uncaught SyntaxError: Unexpected token < - backbone.js

I'm using Underscore templates with BackBone to display the content. Unfortunately I'm receiving the error:
Uncaught SyntaxError: Unexpected token <
The code is:
<script type="text/javascript" id="results-tpl">
<% if(remainingPlaces>0 && remainingPlaces<10){
availability_class = 'limited-availability';
bookable = 'booking__bookable';
}
else if(remainingPlaces>9)
{
availability_class = 'available';
bookable = 'booking__bookable';
}
else{
availability_class = 'sold-out';
bookable = '';
}%>
<div class='booking__event__availability__box' data-eventID='<%-ID%>'>
<span class='time <%=availability_class%> <%=bookable%>'><%=startTime%></span>
<span class='availability'><%=(remainingPlaces>0 && remainingPlaces<10) ? 'Only' : ''%> <%=remainingPlaces%> left</span>
</div>
</script>
I can't seem to figure out why I'm getting the error.
Any help would be appreciated.
Cheers,
Nick

<script type="text/javascript" id="results-tpl"> replace type with: text/template

Related

how can i import data from a Json file with difference format?

How can i add such this to ui-grid? I have a .Json with below format :
0:["date","numberOfTransaction", "price"]
1:["20170207", "3029223", "5294194476028"]
2:["20170208", "2176469", "1479374036275"]
3:["20170209", "2902111", "6971208095034"]
4:["all", "8107803", "13744776607337"]
You should init ui-grid option manually. i.e you should init columnDefs and data array of ui-grid.
Like to this.
angular.forEach($scope.myData,function(data,j){
angular.forEach(data,function(d,i){
if(j == 0)
$scope.gridOptions.columnDefs.push({field:d});
else if(i == 0){
var date = $scope.gridOptions.columnDefs[0];
var numberOfTransaction = $scope.gridOptions.columnDefs[1];
var price = $scope.gridOptions.columnDefs[2];
$scope.gridOptions.data.push({date:data[0],numberOfTransaction:data[1],price:data[2]});
}
}
})
})
Demo
if your JSON is an object you need to access it by the property name.
<div ng-app="app" ng-controller="ctrl">
{{arr['0']}}
</div>
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.arr = {0:["date","numberOfTransaction", "price"],
1:["20170207", "3029223", "5294194476028"],
2:["20170208", "2176469", "1479374036275"],
3:["20170209", "2902111", "6971208095034"],
4:["all", "8107803", "13744776607337"]}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
{{arr['0']}}
</div>

How to create autogenerate ID in angular?

Want to create autogenerate code in angular inputbox on refresh page
like rand(function) in php. Im using this script for this. But problem
is its vanished on page refresh not working properly.
<script type="text/javascript">
function randString(x){
var s = "OL-";
while(s.length<x&&x>0){
var r = Math.random();
s+= (r<0.1?Math.floor(r*100):String.fromCharCode(Math.floor(r*26) + (r>0.5?97:65)));
}
return s;
}
document.getElementById("referal_code").value = randString(10);
</script>
<input required type='text' class='span2' id='referal_code' ng-model='empInfo.referal_code'>
Try this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getNewID() {
try {
var myDate = new Date();
var varID = myDate.getHours() + "" + myDate.getMinutes() + "" + myDate.getSeconds() + "" + myDate.getMilliseconds();
if (varID.Length > 15) {
varID = varID.substr(0, 15);
}
return varID;
} catch (e) {
console.log(e.message);
}
}
function randString(x){
var s = getNewID();
return s;
}
window.onload = function(){
document.getElementById("referal_code").value = randString(10);
}
</script>
</head>
<body>
<input required type='text' class='span2' id='referal_code' ng-model='empInfo.referal_code'>
</body>
</html>
For any attribute in angular world you can use interpolation like this:
<input id="{{randString(10)}}"/>
If you want to have a certain value as id and not get lost after refresh you have to save it on some web storage (localstorage, sessionstorage).
e.g. :
function randString(x){
// ... your function's logic
//Save it in localStorage before returning it
localStorage.inputId = s;
return s;
}
document.getElementById("referal_code").value = localStorage.inputId || randString(10)

My ng-repeat uses bad links

I'm working on a web app using the MEAN stack which is 99% complete except for this persistent error that's been annoying me. I've deployed it to https://find-nightlife.herokuapp.com/#/
My issue is that when you do a search for a location, the web console will always throw these errors:
GET https://find-nightlife.herokuapp.com/%7B%7Bplace.rating_img_url%7D%7D 404 (Not Found)
%7B%7Bplace.image_url%7D%7D:1 GET https://find-nightlife.herokuapp.com/%7B%7Bplace.image_url%7D%7D 404 (Not Found)
Link to the full code on github is here https://github.com/JordanBourne/NightLife
The relevant code:
<section class = "results">
<div ng-repeat = "place in results track by $index | limitTo: 10" class = "resultContainer">
<div class = "resultsList">
<div class = "placeImg"><img src = "{{place.image_url}}" alt = "{{place.name}}"/></div>
<div class = "placeAbout">
<div class = "placeName">
{{place.name}} <img src = "{{place.rating_img_url}}" /></div>
<div class = "placeSnippet">{{place.snippet_text}}</div>
</div>
<div class = "areyouGoing"><span style = "color: red">{{error}}</span> {{place.going}} Going
<button class = "placeGo notGo" ng-click = "plusOne(place, $index)" ng-show = "attend($index)">Not Going</button>
<button class = "placeGo letsGo" ng-click = "plusOne(place, $index)" ng-hide = "attend($index)">Let's Go!</button>
</div>
</div>
<div class = "divider" ng-hide="$last"></div>
</div>
app.controller('NightLifeCtrl', [
'$scope',
'yelp',
'auth',
function ($scope, yelp, auth) {
if(yelp.places.data) {
var attendanceIndex = [];
yelp.bars.forEach(function(bar) {
if (bar.people.indexOf(auth.currentUser()) < 0) {
attendanceIndex.push(0);
} else {
attendanceIndex.push(1);
}
})
$scope.attend = function (num) {
if (attendanceIndex[num] == 1) {
return true;
} else {
return false;
}
}
$scope.results = yelp.bars;
$scope.plusOne = function(place, num) {
if (!auth.isLoggedIn()) {
$scope.error = 'You must be logged in!';
return;
}
yelp.addOne(place);
if (attendanceIndex[num] == 1) {
return attendanceIndex[num] -= 1;
} else {
return attendanceIndex[num] += 1;
}
}
}
}
]);
All the angular.js is in public/js/scripts.js, the guilty ng-repeat is in public/nightlife.html, homepage in views/index.ejs
I appreciate any help!
Replace <img src = "{{ ..}}"> with <img ng-src = "{{ ..}}">. ng-src attribute supports dynamic content.
Always use the ng-href="" attribute when having {{<expressions>}} within your href attributes.
This will stop most of the unwanted behaviour.
Here's the documentation for ng-href.
Quote from the documentation:
The wrong way to write it:
link1
The correct way to write it:
<a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>

AngularJS NG-CSV files not downloading

I am fairly new to AngularJS, i am trying to generate .csv files from an Array using ng-csv.
Now i have tried everything but the files are not generated, i even tried the most simple example i could see on the internet.
I do not see any errors in the error console but still no files are generated.
I am working under windows with XAMPP.
<!DOCTYPE html>
<html ng-app="APP">
<head>
<meta charset="UTF-8">
<title>angular-count-to example</title>
<style type="text/css">
.element{cursor:pointer;float:left;background-color:#ccc;padding:4px;}
</style>
</head>
<body ng-controller="ExampleController">
<p>{{data}}</p>
<button type="button" ng-csv="data" filename="test.csv">Export</button>
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script type="text/javascript" src="bower_components/ng-csv/src/ng-csv/ng-csv.js"></script>
<script>
angular.module('APP',["ngSanitize","ngCsv"]).
controller('ExampleController', function ($scope) {
$scope.filename = "test";
$scope.data = [{a: 1, b:2}, {a:3, b:4}];
});
</script>
</body>
</html>
Above is the simplest example i tried, however even this is not working.
Try out a pure HTML5 Solution. This was a code block i did a while ago. Try customizing for yourself by excluding useless paramaters
function (JSONData, ReportTitle, ShowLabel, reportType, reportName) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
angular.forEach(arrData, function (data, index) {
if (data.date != undefined)
data.date = dateFormat(data.date)
});
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
row += index + ';';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
//var temp = arrData[i][index].toString().replace('.', ',');
//arrData[i][index] = temp;
row += '"' + arrData[i][index] + '";';
}
row = row.split('.').join(",");
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g, "_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
It looks like you are linking to the wrong ng-csv.js. The ng-csv.js file in the bower_components/ng-csv/src/ng-csv/ folder doesn't contain all of the code, you need to use the build version. Try this:
<script type="text/javascript" src="bower_components/ng-csv/build/ng-csv.js"></script>

Angular Smart table + add summary rows

I want to add summary row in Angular smart-table. The rows should not be sorted and it should be added in last.
I had tried but unable to achieve that, and I've searched a lot but was unable to find more information on Google.
Can anyone please let me know what should be the approach to add a summary row?
This kind of sorting can be done using custom sorting algorithm,by adding the same in sortAlgorithm under globalConfig (see smart-table documentation).
try this,
In html,
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link data-require="bootstrap-css#3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script data-require="angular.js#1.2.17" data-semver="1.2.17" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="smart-table.debug.js"></script>
</head>
<body ng-controller="mainCtrl">
<h1>{{greetings}} Plunker!</h1>
<smart-table config="globalConfig" columns="columnsConfig" rows="items"></smart-table>
</body>
</html>
In js file,
angular.module('myApp',['smartTable.table'])
.controller('mainCtrl',['$scope',function(scope,$filter){
scope.greetings="world";
scope.items=[
{name:'mahesh',salary:10000,},
{name:'sachin',salary:15000},
{name:'varun',salary:12000},
{name:'vijay',salary:11000},
{name:'prem',salary:12500},
{name:'gandhi',salary:13000},
{name:'sathish',salary:14500},
{name:'ram',salary:20000},
{name:'siva',salary:22000},
{name:'dilli',salary:18000}
];
var i=0;
scope.totalSalary=0;
scope.calSalary=function(){
for(i=0;i<scope.items.length;i++){
scope.totalSalary=scope.totalSalary+scope.items[i].salary;
}
return scope.totalSalary;
}
var temp={name:'total',salary:scope.calSalary()};
scope.items.push(temp);
scope.globalConfig={
isPaginationEnabled:false,
selectionMode:'single',
sortAlgorithm:function customSortAlgorithm(arrayRef, sortPredicate, reverse) {
var i=0;
var sortTemp='';
var n=arrayRef.length-1;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if(sortPredicate==='salary'){
switch(reverse) {
case true:
if (arrayRef[i].salary > arrayRef[(j)].salary)
{
sortTemp=arrayRef[i];
arrayRef[i]=arrayRef[j];
arrayRef[j]=sortTemp;
}
break;
case false:
if (arrayRef[i].salary < arrayRef[(j)].salary)
{
sortTemp=arrayRef[i];
arrayRef[i]=arrayRef[j];
arrayRef[j]=sortTemp;
}
break;
default:
}}
if(sortPredicate==='name'){
switch(reverse) {
case true:
if (arrayRef[i].name > arrayRef[(j)].name)
{
sortTemp=arrayRef[i];
arrayRef[i]=arrayRef[j];
arrayRef[j]=sortTemp;
}
break;
case false:
if (arrayRef[i].name < arrayRef[(j)].name)
{
sortTemp=arrayRef[i];
arrayRef[i]=arrayRef[j];
arrayRef[j]=sortTemp;
}
break;
default:
}}
}
}
return arrayRef;
}
};
scope.columnsConfig=[
{label:'name',map:'name'},
{label:'salary',map:'salary'}
];
}]);
Please have a look at this plunker for the same.
Hope this solves your problem :)

Resources