Error in calculating distance traveld by user - angularjs

I'm a fresher for ionic and angularjs, I'm developing a tracking app, in which I am not able to calculate the tracked distance and store it in database.
here is my index.html
<!DOCTYPE html>
<html ng-app="starter">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link rel="manifest" href="manifest.json">
<link href="css/ionic.app.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/ng-cordova.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAHe3efHByU2G1ECBpenC8ZpiXlpO7GFXA "></script>
</head>
<body ng-controller="MapCtrl">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Maps</h1>
</ion-header-bar>
<ion-content ng-init="first(User)">
<div class="padding">
<button class="button button-large button-calm" ng-click="starttrack(User)">Start</button>
<button class="button button-large button-assertive" ng-click="endtrack(User)">End</button>
</div>
<div>coordinates = {{getText(User)}}</div>
<button class="button button-small button-balanced" ng-click="dist()">Show distance</button>
</ion-content>
</ion-pane>
</body>
</html>
here is my app.js
.factory('AllServices', function($http) {
return {
drivertrackFunction: function(User) {
var data = { coordinates: User.coordinates,
dis: User.dis};
var link = 'http://localhost/track.php';
return $http.post(link,data);
}
};
})
.controller('MapCtrl', function($scope, filterFilter, $state, $cordovaGeolocation, $interval, AllServices) {
$scope.User = {};
$scope.User.mysrclat= 0;
$scope.User.mysrclong = 0;
$scope.User.timer = "";
$scope.addstring=[];
$scope.addstring1 = [];
$scope.User.string1="";
$scope.User.coordinates=undefined;
$scope.User.string3="";
$scope.lat1 = "";
$scope.lon1 = "";
$scope.lat2 = "";
$scope.lon2 = "";
$scope.User.d = "";
$scope.User.totalDis="";
$scope.originals = [];
$scope.User.temp = 0;
$scope.points = "";
$scope.User.pLen = "";
$scope.User.len = "";
$scope.User.origin1 = "";
$scope.User.destinationB = "";
$scope.User.geocoder = "";
$scope.User.service = "";
$scope.User.originList ="";
$scope.User.destinationList = "";
$scope.User.outputDiv = "";
$scope.User.TotDis = "";
$scope.User.TotDur = "";
$scope.User.dis = 0;
$scope.first = function(User) {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
$scope.User.mysrclat = position.coords.latitude;
$scope.User.mysrclong = position.coords.longitude;
$scope.User.string1 = $scope.User.mysrclat + "," + $scope.User.mysrclong;
console.log($scope.User.mysrclat);
});
}
};
$scope.track = function(User) {
$scope.first(User);
};
function distance(User) {
var R = 6371; // km (change this constant to get miles)
var dLat = ($scope.lat2-$scope.lat1) * Math.PI / 180;
var dLon = ($scope.lon2-$scope.lon1) * Math.PI / 180;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos($scope.lat1 * Math.PI / 180 ) * Math.cos($scope.lat2 * Math.PI / 180 ) * Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
$scope.User.d = R * c;
if ($scope.User.d>1) {
return Math.round($scope.d)+"km";
}
else {
if ($scope.User.d<=1) {
return Math.round($scope.d*1000)+"m";
}
}
return $scope.User.d;
};
$scope.starttrack = function(User) {
$scope.track(User);
$scope.addstring.push($scope.User.string1);
$scope.addstring1.push($scope.User.string1);
var values = $scope.User.string1.split(",");
$scope.lat1 = $scope.User.mysrclat;
$scope.lon1 = $scope.User.mysrclong;
$scope.lat2 = values[0];
$scope.lon2 = values[1];
distance();
$scope.User.timer = $interval(function() {
if($scope.addstring != "") {
$scope.track(User);
$scope.lat1 = $scope.lat2;
$scope.lon1 = $scope.lon2;
$scope.lat2 = $scope.User.mysrclat;
$scope.lon2 = $scope.User.mysrclong;
distance();
console.log($scope.User.d);
$scope.User.dis = $scope.User.dis + $scope.User.d;
$scope.addstring.push("|" + $scope.User.string1);
$scope.addstring1.push($scope.User.string1);
}
}, 10000);
};
$scope.getText = function(User){
return $scope.addstring.join("");
};
$scope.endtrack = function(User, d) {
if(angular.isDefined($scope.User.timer)) {
$interval.cancel($scope.User.timer);
$scope.User.timer = undefined;
$scope.User.string2 = $scope.addstring[0];
for(var i=1; i<($scope.addstring).length; i++) {
$scope.User.string2 = $scope.User.string2 + $scope.addstring[i];
}
$scope.User.coordinates = $scope.User.string2;
$scope.User.dis = $scope.User.dis + " KM";
console.log($scope.User.dis);
AllServices.drivertrackFunction(User)
.then(function(response) {
})
.catch(function(error) {
console.log(error);
});
}
};
$scope.dist = function() {
distance();
console.log($scope.User.d, "Km");
};
})
and this is my php code
<?php
include("connection.php");
$data = json_decode(file_get_contents("php://input"));
$coordinates = $data->coordinates;
$dis = $data->dis;
$q = "INSERT INTO track (Coordinates, Distance) VALUES (:coordinates, :dis)";
$query = $db->prepare($q);
$execute = $query->execute(array(
":coordinates" => $coordinates,
":dis" => $dis
));
echo json_encode($data);
?>

Related

Diffrence between two datetime in desire format using angular js

How to check diffrence between two datetime in desire format using angular js.
var ms = moment($scope.date1,"yyyy-MM-dd HH:mm:ss").diff(moment($scope.date2,"YYYY-MM-DD HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log("Date diff.........",s);
output:
date1........ 2017-12-26 16:20:00
date2........ 2017-12-26 15:10:38
Diff- 01:10
(If should ignore date because there is not date diffrence and if date diffrence is there then it show display like 03:10:05)
Diff (In format- DD-HH-MM)
DD-Days
HH-Hours
MM-Minutes
Tried Code:
$scope.cdate = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
console.log("current time........",$scope.cdate);
$scope.Mydata=Data.timestamp; //I am Getting this data from response
this.getDateDiff = function(cdate, Mydata) {
let d1 = new Date($scope.cdate);
let d2 = new Date($scope.Mydata);
let diff = Math.abs(d1.getTime() - d2.getTime());
let diffDate = new Date(0, 0, 0);
diffDate.setMilliseconds(diff);
let dayMills = ((60**2) * 24) * 1000;
let days = Math.round(diff / dayMills);
function formatNumberString(number) {
return ('0' + number).slice(-2);
}
return {
days: formatNumberString(days),
hours: formatNumberString(diffDate.getHours()),
minutes: formatNumberString(diffDate.getMinutes()),
seconds: formatNumberString(diffDate.getSeconds())
}
}
$scope.dateDiff = this.getDateDiff($scope.cdate, $scope.Mydata);
console.log("days diff.........",$scope.dateDiff);
Output:
Input:
current time- 2017-12-29 10:19:41
Mydata- 2017-02-09 18:16:38
result is coming wrong-
{days: "23", hours: "16", minutes: "03", seconds: "03"}
You can achieve it by using native JavaScript.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.date1 = "2017-12-26 16:20:00";
$scope.date2 = "2017-12-26 15:10:38"
this.getDateDiff = function(date1, date2) {
let d1 = new Date(date1);
let d2 = new Date(date2);
let diff = Math.abs(d1.getTime() - d2.getTime());
let diffDate = new Date(0, 0, 0);
diffDate.setMilliseconds(diff);
let dayMills = ((60**2) * 24) * 1000;
let days = Math.round(diff / dayMills);
function formatNumberString(number) {
return ('0' + number).slice(-2);
}
return {
days: formatNumberString(days),
hours: formatNumberString(diffDate.getHours()),
minutes: formatNumberString(diffDate.getMinutes()),
seconds: formatNumberString(diffDate.getSeconds())
}
}
$scope.dateDiff = this.getDateDiff($scope.date1, $scope.date2);
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
</head>
<body ng-controller="MainCtrl">
<div>date1...... {{date1}}</div>
<div>date2...... {{date2}}</div>
<div>
<span>Diff - </span>
<span ng-if="dateDiff.days > 0">{{dateDiff.days}} : </span>
<span>{{ dateDiff.hours }} : </span>
<span>{{ dateDiff.minutes }}</span>
</div>
</body>
</html>
See if this works for you.
your controller file-
$scope.date1 = "2017-12-26 16:20:00";
$scope.date2 = "2017-12-26 15:10:38";
var diff = moment.utc(date1, "yyyy-MM-DD HH:mm:ss").diff(moment.utc(date2, "yyyy-MM-DD HH:mm:ss"), 'minutes');
var days=diff/(24*60);
var hours=diff/60;
var minutes=diff%60;
$scope.arr = [];
if(parseInt(days)){
arr.push(parseInt(days));
}
if(parseInt(hours)){
arr.push(('0'+hours).substring(-1, 2));
}
if(minutes){
arr.push(('0'+minutes).substring(-1, 2));
}
console.log(arr.join(':'));
Your html file-
...
<div>{{arr.join(':')}}</div>
...

Error with google sign in button

So I have this code:
HTML:
<html ng-app="MyApp" lang="en">
<head>
<title ng-controller="MainController" ng-bind="organisation"></title>
<link ng-controller="MainController" rel="icon" ng-href="{{ logo }}" />
<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyD1mVN9oiWvgp6Zdp5e1pKOiLfdXNplcFo",
authDomain: "testing-environment-98032.firebaseapp.com",
databaseURL: "https://testing-environment-98032.firebaseio.com",
storageBucket: "testing-environment-98032.appspot.com",
};
firebase.initializeApp(config);
</script>
<script src="scripts/angular.min.js"></script>
<script src="scripts/angular-sanitize.min.js"></script>
<link rel="stylesheet" href="stylesheets/index.css" />
</head>
<body ng-controller="MainController" ng-init="initialize()">
<div id="googleSignIn" ng-style="googleSignInStyle" ng-click="signUserIn()" ng-bind="googleSignInText"></div>
<span ng-click="signOut()" >Sign Out!</span>
<article id="scrollSpeedValue" class="valuePasser"><?php echo $scrollSpeed; ?></article>
<div id="h1-margin"> </div>
<center><span class="h1"><b ng-bind="organisation"></b></span></center>
<div class="main">
<span ng-bind-html="generateNavBar(navBar.common, navBar.common[0])"></span>
<marquee id="EventsMarquee" class="infoBanner" direction="left" scrollamount="10">Events here! Set initial speed to 1000000000</marquee>
<div class="main-body" id="main-body">
<center><i>Welcome to the -- site!</i></center><br>
<div style="width: 48%; float: left;">
Description
</div>
<div style="width: 48%; float: right;"><iframe src="http://www.google.com" style="width: 99%; height: 373px;"></iframe></div>
</div>
<div class="main-body" id="footer-links">
<center>
Resources | organisation Resources | link | Edit!
</center>
</div>
</div>
<footer>
<br>
</footer>
<script src="scripts/app.js"></script>
</body>
</html>
AngularJS:
var app = angular.module("MyApp", ["ngSanitize"]);
app.controller("MainController", ["$scope", function ($scope){
$scope.organisation = "Organisation Name";
$scope.logo = "http://www.weboniks.com/images/logos/logo5.jpg";
$scope.googleSignInStyle = {};
$scope.googleSignInText = "";
$scope.signInVariables = {
displayName: null,
email: null,
uid: null,
photoURL: null
}
$scope.navBar = {
common: [
["Home", "index.html"],
["Resources", "index.html"],
["Staff Resources", "index.html"],
[$scope.organisation + " Resources", "index.html"],
["Who we are", "index.html"]
]
}
$scope.signIn = function (){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
var providerData = user.providerData[0];
firebase.database().ref('users/' + providerData.displayName).set({Email: providerData.email, PhotoURL: providerData.photoURL, uid: providerData.uid});
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
console.log ("Error! Error code: " + errorCode + ", Email: " + email + ", Credential: " + credential + ". That's all we know.");
});
}
$scope.onSignIn = function (){
var providerData = firebase.auth().currentUser.providerData[0];
if (providerData.photoURL == null)
{
$scope.googleSignInStyle["background"] = "url(../images/img_default_profile.png)";
}
else
{
$scope.googleSignInStyle["background"] = providerData.photoURL;
}
$scope.googleSignInStyle["background-size"] = "100%";
$scope.googleSignInStyle["background-repeat"] = "no-repeat";
$scope.googleSignInStyle["border-radius"] = "100%";
$scope.googleSignInStyle["width"] = "4.5%";
$scope.googleSignInStyle["height"] = "9%";
$scope.googleSignInStyle["cursor"] = "default";
}
$scope.checkSignIn = function (){
var user = firebase.auth().currentUser;
if (user == null)
{
setTimeout(function (){ $scope.checkSignIn(); }, 1);
}
else
{
$scope.onSignIn();
}
}
$scope.signUserIn = function (){
var user = firebase.auth().currentUser;
if (user == null)
{
$scope.signIn();
setTimeout(function (){ $scope.checkSignIn() }, 10000);
}
else
{
$scope.onSignIn();
}
}
$scope.signOut = function (){
firebase.auth().signOut();
$scope.googleSignInText = "";
$scope.googleSignInStyle["background"] = "url(../images/btn_google_signin_dark_normal_web#2x.png)";
$scope.googleSignInStyle["background-size"] = "100%";
$scope.googleSignInStyle["background-repeat"] = "no-repeat";
$scope.googleSignInStyle["border-radius"] = "0%";
$scope.googleSignInStyle["width"] = "12%";
$scope.googleSignInStyle["height"] = "6%";
$scope.googleSignInStyle["cursor"] = "default";
$scope.googleSignInStyle["cursor"] = "pointer";
}
$scope.generateNavBar = function (items, current){
var navigator = '<nav><ul><b>';
for (i = 0; i < items.length; i++)
{
if (items[i] == current)
{
navigator += '<li id="current">' + items[i][0] + '</li>';
}
else
{
navigator += '<li>' + items[i][0] + '</li>';
}
}
navigator += '</b></ul></nav>';
console.log (navigator);
return navigator;
}
}]);
This code is supposed to sign a user in with google and then change the sign in with google button to their profile image. It works fine, the only issue is that the first time you click the sign in button it only signs you in. Then you have to click it again to change the button to the users image. Is there something I have done wrong?

Change Different type of Attributes for Dynamically added every element

How can I Change (type) Attribute for each added dynamic buttons? In below code, label names were changing perfectly, but when i am trying to change button types it is applying to all added dynamic buttons,
My requirement is have to change every button type with different types (means: first added button type to submit, second added type to reset, third added button to cancel). but in my code if i change second button type to 'Reset' at the same time the first button type also going to Reset type... can u please tell me how can i change button type for every added element ...
Working DEMO
Updated:
var app = angular.module('myapp', ['ngSanitize']);
app.controller('MainCtrl', function($scope, $compile) {
var counter = 0;
$scope.buttonFields = [];
$scope.add_Button = function(index) {
$scope.buttonFields[counter] = {button: 'Submit'};
var buttonhtml = '<div ng-click="selectButton(buttonFields[\'' + counter + '\'])"><button id="button_Type">{{buttonFields[' + counter + '].button}}</button>//click//</div>';
var button = $compile(buttonhtml)($scope);
angular.element(document.getElementById('add')).append(button);
$scope.changeTosubmit = function (val) {
$scope.buttonField = val;
var els = document.body.querySelectorAll('#button_Type');
for (var i = 0, ils = els.length; i < ils; i++) {
var el = els[i];
el.setAttribute("type", "submit");
compile(el);
}
};
$scope.changeToreset = function (val) {
$scope.buttonField = val;
var els = document.body.querySelectorAll('#button_Type');
for (var i = 0, ils = els.length; i < ils; i++) {
var el = els[i];
el.setAttribute("type", "reset");
compile(el);
}
};
$scope.changeTocancel = function (val) {
$scope.buttonField = val;
var els = document.body.querySelectorAll('#button_Type');
for (var i = 0, ils = els.length; i < ils; i++) {
var el = els[i];
el.setAttribute("type", "cancel");
compile(el);
}
};
++counter;
};
$scope.selectButton = function (val) {
$scope.buttonField = val;
$scope.showButton_Types = true;
};
});
function compile(element) {
var el = angular.element(element);
$scope = el.scope();
$injector = el.injector();
$injector.invoke(function ($compile) {
$compile(el)($scope);
});
};
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="add_Button($index)">Add Buttons</button>
<hr>
<div id="add"></div>
<form ng-show="showButton_Types">
<div>
<label>Button Name(?)</label><br/>
<input ng-model="buttonField.button">
</div>
<div>
<label>change button types(?)</label><br/>
<input ng-click="changeTosubmit(buttonFields['' + counter + ''])" name="submit" type="radio"> Submit
<input ng-click="changeToreset(buttonFields['' + counter + ''])" name="submit" type="radio"> Reset
<input ng-click="changeTocancel(buttonFields['' + counter + ''])" name="submit" type="radio"> Cancel
</div>
</form>
</body>
</html>

Ionic/Angular custom directive and ionic list thumbnail

I created a custom directive, chess-board, showing a chess position. With Ionic framework, I generate a list of chess-board, and would like to thumbnail chess-board on the left. Though I followed documentation, but using svg instead, as my directive generate svg, I can't get the desired layout.
Here is my JsBin (don't worry for missing pictures).
Here is index.html :
<!DOCTYPE html>
<html>
<head>
<script src="//code.ionicframework.com/1.0.0-beta.13/js/ionic.bundle.min.js"></script>
<link href="//code.ionicframework.com/1.0.0-beta.13/css/ionic.min.css" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-app="static-board">
<ion-pane>
<ion-header-bar class="bar-dark">
<h1 class="title">Chess Positions Archiver</h1>
</ion-header-bar>
<ion-content>
<div class="list">
<a class="item item-thumbnail-left" href="#">
<chess-board cells-size="30" fen="3rr1k1/pb5p/1qp3pB/1pn1Q3/8/7P/PPP3P1/R3KR2 b - - 0 1" show-coords> </chess-board>
<h3>Exercise 1</h3>
</a>
<a class="item item-thumbnail-left" href="#">
<chess-board cells-size="30" show-coords></chess-board>
<h3>Exercise 2</h3>
</a>
</div>
</ion-content>
</ion-pane>
</body>
</html>
Here is my script
(function(){
var chessPieces = {
'P': 'wp',
'N': 'wn',
'B': 'wb',
'R': 'wr',
'Q': 'wq',
'K': 'wk',
'b': 'bb',
'p': 'bp',
'n': 'bn',
'r': 'br',
'q': 'bq',
'k': 'bk'
};
angular.module('static-board', ['ionic'])
.factory('chessPictures', [function(){
return {
getPicture: function(pieceFen){
return chessPieces[pieceFen];
}
}
}])
.directive('chessBoard', [function(){
function getBoardHtml(cellsSize, positionFen, showCoords){
// taken from http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
function sprintf() {
var args = arguments,
string = args[0],
i = 1;
return string.replace(/%((%)|s|d)/g, function (m) {
// m is the matched format, e.g. %s, %d
var val = null;
if (m[2]) {
val = m[2];
} else {
val = args[i];
// A switch statement so that the formatter can be extended. Default is %s
switch (m) {
case '%d':
val = parseFloat(val);
if (isNaN(val)) {
val = 0;
}
break;
}
i++;
}
return val;
});
}
function fenToPosition(){
function getSingleLine(lineFen){
var result = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
var column = 0;
for (var index in lineFen){
var currElem = lineFen[index];
var isDigit = !isNaN(parseInt(currElem));
if (isDigit){
column += parseInt(currElem);
}
else {
result[column] = currElem;
column++;
}
}
return result;
}
var result = [];
var parts = positionFen.split(" ")[0].split("/");
for (var partIndex in parts){
var currPart = parts[partIndex];
result.push(getSingleLine(currPart));
}
return result;
}
function getBackground(size){
return sprintf("<rect x='0' y='0' width='%d' height='%d' fill='#BAA' />", size, size);
};
function getCells(){
function getSingleCell(cellX, cellY){
var x = cellX*cellsSize + cellsSize/2;
var y = cellY*cellsSize + cellsSize/2;
var color = (cellX+cellY)%2 === 0 ? "#E9E637" : "#7C4116";
return sprintf("<rect x='%d' y='%d' width='%d', height='%d' fill='%s' />",
x,y, cellsSize, cellsSize, color);
}
var result = "";
for (var line = 0; line < 8; line++){
for (var col = 0; col < 8; col++){
result += getSingleCell(col, line)+'\n';
}
}
return result;
}
function getPieces(positionPieces){
function getSinglePiece(cellX, cellY){
var x = cellX*cellsSize + cellsSize/2;
var y = cellY*cellsSize + cellsSize/2;
var pieceFen = positionPieces[cellY][cellX];
var piecePictureRef = chessPieces[pieceFen];
var path = sprintf("../img/chess_pieces/%s.svg", piecePictureRef);
return piecePictureRef ? sprintf("<image x='%d' y='%d' width='%d' height='%d' xlink:href='%s' />",
x, y, cellsSize, cellsSize, path
) : undefined;
}
var result = "";
for (var rank = 0; rank < 8; rank++){
for (var file = 0; file < 8; file++){
var line = getSinglePiece(file, rank);
if (line) {
result += line+'\n';
}
}
}
return result;
}
function getPlayerTurn(){
var turnStr = positionFen.split(" ")[1];
var color = turnStr === "w" ? "#FFF" : "#000";
var location = parseInt(8.5*cellsSize);
var size = cellsSize / 2;
return sprintf("<rect x='%d' y='%d' width='%d' height='%d' fill='%s'/>",
location, location, size, size, color);
}
function getCoordinates(){
result = "";
var files = "ABCDEFGH";
for (var index in files){
var currFile = files[index];
result += sprintf("<text x='%d' y='%d' fill='#000' font-size='%d'>%s</text>",
parseInt(cellsSize*index + cellsSize*.8), parseInt(cellsSize*.45),
parseInt(cellsSize*.4), currFile);
result += sprintf("<text x='%d' y='%d' fill='#000' font-size='%d'>%s</text>",
parseInt(cellsSize*index + cellsSize*.8), parseInt(cellsSize*8.9),
parseInt(cellsSize*.4), currFile);
}
var ranks = "87654321";
for (var index in ranks){
var currRank = ranks[index];
result += sprintf("<text x='%d' y='%d' fill='#000' font-size='%d'>%s</text>",
parseInt(cellsSize*.1), parseInt(cellsSize*1.25+cellsSize*index),
parseInt(cellsSize*.4), currRank);
result += sprintf("<text x='%d' y='%d' fill='#000' font-size='%d'>%s</text>",
parseInt(cellsSize*8.7), parseInt(cellsSize*1.25+cellsSize*index),
parseInt(cellsSize*.4), currRank);
}
return result;
}
var size = 9*cellsSize;
var result = sprintf("<svg width='%d' height='%d'>\n%s\n%s\n%s\n%s\n%s\n</svg>",
size, size, getBackground(size), getCells(), getPieces(fenToPosition()),
getPlayerTurn(), showCoords ? getCoordinates() : "");
return result;
}
return {
restrict: 'E',
link: {
post : function(scope, element, attrs){
var cellsSize = attrs.cellsSize || 20;
var positionFen = attrs.fen || 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w';
var showCoords = attrs.showCoords !== undefined ? true : false;
var newElem = angular.element(getBoardHtml(cellsSize, positionFen, showCoords));
element.replaceWith(newElem);
}
}
}
}])
})();
So what's wrong ?
Is that the fact that I am using an <svg> instead of an <img> ?
Or is it something else ?
you will need to do several things:
wrap svg into a div, and give it class item-image
<div class="item-image">
<chess-board cells-size="30"></chess-board>
</div>
then, when you create the SVG, you will need to set properties like this:
width="100%" height="100%" viewBox="0,0,270,270"
width and hight will tell it how to behave inside it's container, while viewBox property sets the size of canvas, on which the image will be drawn.
this line
var result = sprintf("<svg width='%d' height='%d'>\n%s\n%s\n%s\n%s\n%s\n</svg>", size, size, getBackground(size), getCells(), getPieces(fenToPosition()), getPlayerTurn(), showCoords ? getCoordinates() : "");
should look like this
var result = sprintf("<svg width='100%%' height='100%%' viewBox='0,0,%d,%d'>\n%s\n%s\n%s\n%s\n%s\n</svg>", size, size, getBackground(size), getCells(), getPieces(fenToPosition()), getPlayerTurn(), showCoords ? getCoordinates() : "");
You can see it here http://jsbin.com/basimodufa/1/edit?html,js,output
there is a good resource on SVG sizing/containing here

How to update angular progress bar every time I click

Hi I am using angular progress bar and I want to update every time I click a button.
<div ng-controller="ProgressDemoCtrl">
<br/>
<h3>
Dynamic
<button class="btn btn-sm btn-primary" ng-click="random()" type="button">Randomize</button>
</h3>
<small>
<em>No animation</em>
</small>
<progressbar animate="false" type="success" value="dynamic">
<b>{{dynamic}}%</b>
</progressbar>
</div>
ANGULAR
var ProgressDemoCtrl = function ($scope) {
$scope.max = 00;
$scope.random = function() {
var value = Math.floor((Math.random() * 100) + 1);
var type;
if (value < 25) {
type = 'success';
} else if (value < 50) {
type = 'info';
} else if (value < 75) {
type = 'warning';
} else {
type = 'danger';
}
$scope.showWarning = (type === 'danger' || type === 'warning');
$scope.dynamic = value;
$scope.type = type;
};
$scope.random();
$scope.randomStacked = function() {
$scope.stacked = [];
var types = ['success', 'info', 'warning', 'danger'];
for (var i = 0, n = Math.floor((Math.random() * 4) + 1); i < n; i++) {
var index = Math.floor((Math.random() * 4));
$scope.stacked.push({
value: Math.floor((Math.random() * 30) + 1),
type: types[index]
});
}
};
$scope.randomStacked();
};
as you can see in here what it does when i click the button is filling it up randomly.So what i want to do is be able to click a button and update the progress bar.
If you are using angular bootstrap's progressbar this is very easy. I just made a plunkr for it.
Your HTML
<div ng-controller="ProgressDemoCtrl">
<h3>Progress bar value is {{dynamic}}</h3>
<progressbar max="max" value="dynamic">
<span style="color:black; white-space:nowrap;">
{{dynamic}} / {{max}}
</span>
</progressbar>
<input type="button" ng-click="progress()" value="Click Me To Progress" />
</div>
</body>
</html>
and JS
angular.module('plunker', ['ui.bootstrap']);
var ProgressDemoCtrl = function ($scope) {
$scope.dynamic = 10;
$scope.max = 100;
$scope.progress = function(){
$scope.dynamic = $scope.dynamic + 10;
};
};

Resources