Having trouble dealing with Moment JS (Angular) - angularjs

I am having trouble with Moment JS. Basically, I have some metadata for a radio station, and in my php call, I get in return the 'duration' of the song, the 'timestamp' when the song started.
I did some calculation with Moment JS to get the time when the song will be finished, and then I find the difference. However, the difference is returning a negative number, which then breaks the app.
If someone can help me that would be great.
This is my plunk http://plnkr.co/edit/joVLYdTKY5dZBOTNfTOI
Services
angular.module('starter', [])
.run(function(CurrentTrack){
CurrentTrack.refreshTrackData();
})
.controller('radioCtrl', function($scope,CurrentTrack) {
console.log(CurrentTrack);
$scope.CurrentTrack = CurrentTrack;
})
.service('CurrentTrack',function(radioData,$timeout){
var currentTrack = this;
this.setTrackData = function(trackData){
currentTrack.coverUrl = trackData.cover_url;
currentTrack.title = trackData.title;
currentTrack.artist = trackData.artist;
currentTrack.duration = moment.duration(parseInt(trackData.duration));
currentTrack.startedAt = moment.unix(trackData.timestamp);
currentTrack.finishesAt = moment(this.startedAt.add(this.duration));
currentTrack.updateIn = this.finishesAt.diff(moment());
currentTrack.refreshing = false;
return currentTrack.updateIn;
}
this.refreshTrackData = function(){
currentTrack.refreshing = true;
return radioData.refresh()
.then(currentTrack.setTrackData.bind(currentTrack))
.then(currentTrack.scheduleUpdate);
}
this.scheduleUpdate = function(ms){
console.log(ms)
$timeout(function(){
currentTrack.refreshTrackData()
},ms);
return;
}
})
Factory
.factory('radioData', function($http,$timeout) {
var retries = 0;
function parseResponse(response){
retries = 0;
if(!response.data.results){
console.log('no results')
return false;
}
console.log('refreshed...')
return response.data.results[0];
}
function makeRequest(){
console.log('refreshing...')
return $http.get('http://radio-sante-animale.fr/blah11.php? callback=jsonpCallback')
}
function retry(errResponse){
console.error('timed out');
//wait for a sec
retries++;
if(retries > 5){
throw new Error('timed out after 5 attempts!');
}
//oops
return $timeout(makeRequest,1000).then(null,retry);
}
var radioData = {
refresh: function() {
return makeRequest()
.then(null,retry)
.then(parseResponse)
.catch(function(err){
console.log(err);
});
}
};
return radioData;
});

From my side, it worked by adding Math.abs in your $timeout method
this.scheduleUpdate = function(ms) {
console.log( 'update in :' + ms)
$timeout(function() {
currentTrack.refreshTrackData()
}, Math.abs(ms));
return;
}

First I changed:
currentTrack.finishesAt = moment(this.startedAt.add(this.duration));
to:
currentTrack.finishesAt = moment(currentTrack.startedAt).add(currentTrack.duration);
In the original code you are mutating the startedAt time then cloning. I also changed all the this to currentTrack to make it more consistent.
The problem
The bug manifests when there is a difference in the time the server is keeping and the time that the client is keeping, (not because you have anything reversed).
Basically the server sends you trackData.timestamp which you parse and convert into a moment to use as your startedAt time. Then you change the trackData.duration into a moment.duration and add it to the startedAt time to get your finishesAt time.
If the time that the client is keeping is running ahead the server's time, the calculated finishesAt time will be earlier than when the actual song ends. An exaggerated example makes this more clear.
var app = angular.module('app', []);
app.controller('myController', function($scope, $timeout, $interval, Server) {
function updateTime() {
$scope.serverTime = moment().subtract(1,'s');
$scope.clientTime = moment();
}
function refreshInfo() {
Server.getSongInfo().then(parseInfo).then(scheduleRefresh);
};
function parseInfo(trackData) {
$scope.songInfo = trackData;
var startedAt = trackData.timestamp;
$scope.finishesAt = moment(startedAt).add(trackData.duration, 'ms');
$scope.updateIn = $scope.finishesAt.diff(moment());
return $scope.updateIn;
}
function scheduleRefresh(updateIn) {
if (updateIn < 0) {
$scope.bugged = true;
} else {
$scope.bugged = false;
}
$timeout(refreshInfo, updateIn);
}
$scope.songInfo = "loading";
updateTime();
refreshInfo();
$interval(updateTime, 1000);
});
app.service('Server', function($timeout, $interval) {
var song = {
duration: 5000
};
this.getSongInfo = function() {
return $timeout(function() { return this.trackData });
};
function nextSong() {
this.trackData = {
duration: song.duration,
timestamp: moment().subtract(1,'s')
};
}
nextSong();
$interval(nextSong, song.duration);
});
.container {
display: flex;
flex-flow: row wrap;
}
.row {
display: flex;
flex-direction: row;
flex-flow: space-around;
width: 100%;
}
.col {
margin: auto;
text-align: center;
}
.red {
background-color: red;
}
<head>
<script data-require="angular.js#1.4.0-beta.3" data-semver="1.4.0-beta.3" src="https://code.angularjs.org/1.4.0-beta.3/angular.js"></script>
<script data-require="moment.js#2.8.3" data-semver="2.8.3" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
</head>
<div ng-app='app' ng-controller='myController'>
<div class="container">
<div class='row'>
<div class='col' ng-class='{red:bugged}'>
<h3>Song Info</h3>
<div>{{ songInfo }}</div>
</div>
</div>
<div class="row">
<div class='col'>
<h3>Server</h3>
<div>{{ serverTime.format("hh:mm:ss") }}</div>
</div>
<div class='col'>
<h3>Finishes At</h3>
<div>{{ finishesAt.format("hh:mm:ss") }}</div>
</div>
<div class='col'>
<h3>Update In</h3>
<div>{{ updateIn }}</div>
</div>
<div class='col'>
<h3>Client</h3>
<div>{{ clientTime.format("hh:mm:ss") }}</div>
</div>
</div>
</div>
</div>
Whenever the song info div is red, the client is in the loop where it is requesting new track info and parsing out a finish time that is earlier than the current moment, which immediately makes it request new track info.
angular.module('starter', [])
.run(function(CurrentTrack) {
CurrentTrack.refreshTrackData();
})
.controller('radioCtrl', function($scope, CurrentTrack) {
$scope.CurrentTrack = CurrentTrack;
})
.service('CurrentTrack', function(radioData, $timeout) {
var currentTrack = this;
this.setTrackData = function(trackData) {
currentTrack.coverUrl = trackData.cover_url;
currentTrack.title = trackData.title;
currentTrack.artist = trackData.artist;
currentTrack.duration = moment.duration(parseInt(trackData.duration));
currentTrack.startedAt = moment.unix(trackData.timestamp);
currentTrack.finishesAt = moment(currentTrack.startedAt).add(currentTrack.duration);
currentTrack.updateIn = currentTrack.finishesAt.diff(moment())
console.log(currentTrack, trackData);
currentTrack.refreshing = false;
return currentTrack.updateIn;
}
this.refreshTrackData = function() {
currentTrack.refreshing = true;
return radioData.refresh()
.then(currentTrack.setTrackData)
.then(currentTrack.scheduleUpdate);
}
this.scheduleUpdate = function(ms) {
console.log("update in " + ms)
$timeout(function() {
currentTrack.refreshTrackData()
}, ms);
return;
}
})
.factory('radioData', function($http, $timeout) {
var retries = 0;
function parseResponse(response) {
retries = 0;
if (!response.data.results) {
console.log('no results')
return false;
}
console.log('response parsed.')
return response.data.results[0];
}
function makeRequest() {
console.log('making request.')
return $http.get('http://radio-sante-animale.fr/blah11.php?callback=jsonpCallback')
}
function retry(errResponse) {
console.error('timed out');
//wait for a sec
retries++;
if (retries > 5) {
throw new Error('timed out after 5 attempts!');
}
//oops
return $timeout(makeRequest, 1000).then(parseResponse, retry);
}
var radioData = {
refresh: function() {
return makeRequest()
.then(parseResponse, retry)
.catch(function(err) {
console.log(err);
});
}
};
return radioData;
});
<!DOCTYPE html>
<html ng-app="starter">
<head>
<script data-require="angular.js#1.4.0-beta.3" data-semver="1.4.0-beta.3" src="https://code.angularjs.org/1.4.0-beta.3/angular.js"></script>
<script data-require="moment.js#2.8.3" data-semver="2.8.3" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
</head>
<body ng-controller="radioCtrl">
<h3>Current Music Information</h3>
<p ng-show="CurrentTrack.refreshing">refreshing...</p>
<img style="width:300px;height:300px;" src="{{CurrentTrack.coverUrl}}" alt="">
<p>
Title : {{ CurrentTrack.title }}
<br />Artist : {{ CurrentTrack.artist }}
<br />The song started at {{ CurrentTrack.startedAt }}
<br />Duration of the song {{ CurrentTrack.duration.asSeconds() }} seconds
<br />Finishes At {{ CurrentTrack.finishesAt }}
<br />Update In {{ CurrentTrack.updateIn }}
<br />
</body>
</html>
I'm actually not sure the best approach to fixing this problem but hopefully some one has a better answer.
A hack solution is to add more time (some acceptable amount of error) to the finishesAt to give a little leeway.
currentTrack.finishesAt = moment(currentTrack.startedAt).add(currentTrack.duration).add(1, 's');

From http://momentjs.com/docs/#/displaying/difference/
If the moment is earlier than the moment you are passing to
moment.fn.diff, the return value will be negative.
You need to reverse the dates in your diff.
EDIT: Like this -
currentTrack.updateIn = moment().diff(this.finishesAt);

Related

How can I make square-connect work with angularjs?

Basing myself on the example provided by the SquareUp documentation (https://github.com/square/connect-api-examples.git). I am trying to integrate squareup to process payments with CC but I do not know what happens.
the view:
<div class="bg-light lter b-b wrapper-md">
<h1 class="m-n font-thin h3"></h1>
</div>
<div class="wrapper-md" >
<div class="row">
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-heading font-bold">CC info</div>
<div class="panel-body">
<div class="no-boot" ng-controller="PaymentController" ng-cloak>
<div id="successNotification" ng-show="isPaymentSuccess">
Card Charged Succesfully!!
</div>
<form novalidate id="payment-form" ng-hide="isPaymentSuccess">
<div id="card-errors" ng-repeat="error in card_errors">
<li>{{error.message}}</li>
</div>
<div>
<label>Card Number</label>
<div ng-model="data.card.card_number" id="sq-card-number"></div>
</div>
<div>
<label>CVV</label>
<div ng-model="data.card.cvv" id="sq-cvv"></div>
</div>
<div>
<label>Expiration Date</label>
<div ng-model="data.card.expiration_date" id="sq-expiration-date"></div>
</div>
<div>
<label>Postal Code</label>
<div ng-model="data.card.postal_code" id="sq-postal-code"></div>
</div>
<div>
<input ng-click="submitForm()" ng-disabled="isProcessing" type="submit" id="submit" value="Buy Now" class="btn btn-primary">
</div>
</form>
<button id="sq-apple-pay" class="button-apple-pay-block" ng-show="supportApplePay"></button>
</div>
</div>
</div>
</div>
</div>
</div>
the controller:
'use strict';
/* Controllers */
// signin controller
app.controller('PaymentController', ['$scope', '$http', function($scope, $http) {
//for showing #successNotification div
$scope.isPaymentSuccess = false;
//for disabling payment button
$scope.isProcessing = false;
//for disabling apple pay button
$scope.supportApplePay = false;
$scope.data = {
product_id: "001",
user: {},
card: {},
products: {
"001": {
"name": "Paper Origami 1:10,000 scale model (11 inch)",
"value":"1.0",
},
"002": {
"name": "Plastic 1:5000 scale model (22 inch)",
"value":"49.0",
},
"003": {
"name": "Metal & Concrete 1:1000 scale replica (9 feet)",
"value":"5000.0",
}
}
};
$scope.submitForm = function(){
console.log($scope.data)
$scope.isProcessing = true;
$scope.paymentForm.requestCardNonce();
return false
}
var cardNumber = $scope.data.card.card_number = 5409889944179029;
var cvv = $scope.data.card.cvv = 111;
var expirationDate = $scope.data.card.expirationDate = '02/21';
var postalCode = $scope.data.card.postalCode = 3311;
$scope.paymentForm = new SqPaymentForm({
applicationId: 'sandbox-sq0idp-IsHp4BXhhVus21G5JPyYpw',
locationId: 'CBASECJCvmqtoIL1fn3iReEjQRcgAQ',
inputClass: 'sq-input',
inputStyles: [
{
fontSize: '14px',
padding: '7px 12px',
backgroundColor: "transparent"
}
],
cardNumber: {
elementId: 'sq-card-number',
placeholder: '5409889944179029',
value: '5409889944179029'
},
cvv: {
elementId: 'sq-cvv',
placeholder: '111',
value: '111'
},
expirationDate: {
elementId: 'sq-expiration-date',
placeholder: '04/21',
value: '04/21'
},
postalCode: {
elementId: 'sq-postal-code',
placeholder: '33114',
value: '33114'
},
applePay: {
elementId: 'sq-apple-pay'
},
// cardNumber:''+cardNumber,
// cvv:''+cvv,
// expirationDate:''+expirationDate,
// postalCode:''+postalCode,
callbacks: {
cardNonceResponseReceived: function(errors, nonce, cardData) {
if (errors){
$scope.card_errors = errors
$scope.isProcessing = false;
$scope.$apply(); // required since this is not an angular function
}else{
$scope.card_errors = []
$scope.chargeCardWithNonce(nonce);
}
},
unsupportedBrowserDetected: function() {
// Alert the buyer
},
methodsSupported: function (methods) {
console.log(methods);
$scope.supportApplePay = true
$scope.$apply(); // required since this is not an angular function
},
createPaymentRequest: function () {
var product = $scope.data.products[$scope.data.product_id];
return {
requestShippingAddress: true,
currencyCode: "USD",
countryCode: "US",
total: {
label: product["name"],
amount: product["value"],
pending: false,
}
};
},
// Fill in these cases to respond to various events that can occur while a
// buyer is using the payment form.
inputEventReceived: function(inputEvent) {
switch (inputEvent.eventType) {
case 'focusClassAdded':
// Handle as desired
break;
case 'focusClassRemoved':
// Handle as desired
break;
case 'errorClassAdded':
// Handle as desired
break;
case 'errorClassRemoved':
// Handle as desired
break;
case 'cardBrandChanged':
// Handle as desired
break;
case 'postalCodeChanged':
// Handle as desired
break;
}
}
}
});
$scope.chargeCardWithNonce = function(nonce) {
alert("no");
var url = "libs/php_payment/process-card.php";
var data = {
nonce: nonce,
product_id: $scope.data.product_id,
name: $scope.data.user.name,
email: $scope.data.user.email,
street_address_1: $scope.data.user.street_address_1,
street_address_2: $scope.data.user.street_address_2,
city: $scope.data.user.city,
state: $scope.data.user.state,
zip: $scope.data.user.zip
};
$http.post(url, data).success(function(data, status) {
if (data.status == 400){
// display server side card processing errors
$scope.isPaymentSuccess = false;
$scope.card_errors = []
for (var i =0; i < data.errors.length; i++){
$scope.card_errors.push({message: data.errors[i].detail})
}
}else if (data.status == 200) {
$scope.isPaymentSuccess = true;
}
$scope.isProcessing = false;
}).error(function(){
$scope.isPaymentSuccess = false;
$scope.isProcessing = false;
$scope.card_errors = [{message: "Processing error, please try again!"}];
})
}
//build payment form after controller loads
var init = function () {
$scope.paymentForm.build()
};
init();
}]);
error: "Error: [$rootScope:inprog] $digest already in progress
I haven't done angular in a while, but I'm betting that your issue is in:
methodsSupported: function (methods) {
console.log(methods);
$scope.supportApplePay = true
$scope.$apply(); // required since this is not an angular function
},
You are calling $apply() after a non-asyc call, generally you apply new data that you got asynchronously. See Angular Docs

Angular - how to make $interval work from user input

I am taking date and time from user as input and then wanted to display it interval in label
After that datetime completes I want to make that label color change.
Please guide me how can i achieve this.
https://codepen.io/shreyag020/pen/vKvmdx
$interval(function(){
todoTime=$scope.datetime;
});
Here is an example of how you could change the background color of a div over time. Clicking the start button begins a countdown timer from 1 minute. It starts out with no background, once the timer is started it turns green, at 15 seconds before time runs out it turns orange and when the time has run out it turns red. The change of the background color is animated using ng-class, ngAnimate and the animation hooks.
angular.module('app', ['ngAnimate'])
.controller('ctrl', function($scope, $interval) {
var timerPromise;
$scope.reset = function() {
$scope.userTime = new Date;
$scope.userTime.setMinutes(1);
$scope.userTime.setSeconds(0);
$scope.resetVisible = false;
$scope.started = false;
}
$scope.start = function() {
$scope.started = true;
$scope.resetVisible = false;
timerPromise = $interval(function() {
if ($scope.userTime.getSeconds() > 0 || $scope.userTime.getMinutes() > 0) {
$scope.userTime.setTime($scope.userTime.getTime() - 1000);
}
}, 1000);
}
$scope.pause = function() {
$interval.cancel(timerPromise);
$scope.started = false;
$scope.resetVisible = true;
}
$scope.timeBackground = function() {
if ($scope.started) {
if ($scope.userTime.getMinutes() === 0 && $scope.userTime.getSeconds() === 0) {
$scope.resetVisible = true;
$interval.cancel(timerPromise);
return 'expired';
}
if ($scope.userTime.getMinutes() === 0 && $scope.userTime.getSeconds() <= 15) {
return 'warning';
}
return 'ok';
}
return 'clear';
}
$scope.reset();
});
.timeDisplay {
color: white;
font-weight: bold;
}
.ok-add,
.ok-remove,
.warning-add,
.warning-remove,
.expired-add,
.expired-remove {
transition: background-color 1000ms linear;
}
.warning,
.warning-add.pre-warning-add-active {
background-color: orange;
}
.expired,
.expired-add.expired-add-active {
background-color: red;
}
.ok,
.ok-add.ok-add-active {
background-color: green;
}
.clear {
background-color: none;
color: black;
}
div {
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div class="timeDisplay" ng-class="timeBackground()">
Time remaining: {{userTime | date: 'mm:ss'}}
</div>
<div ng-if="!started">
<button ng-click="start()">Start</button>
</div>
<div ng-if="started">
<button ng-click="pause()">Pause</button>
</div>
<div ng-if="resetVisible">
<button ng-click="reset()">Reset</button>
</div>
</div>

$scope array not getting updated

Inside a controller I have this code:
$rootScope.$on('chat_contact', function(event, data) {
var message = data.message;
if(data.key === 'IM_MSG') {
console.log("chat_contact.........");
var contact = $scope.contacts[message.sndrId];
if(contact) {
contact.lastMsg = message.text;
contact.sndrName = message.sndrName;
} else {
$scope.contacts[7] = {
'lastMsg': message.text,
'sndrName': message.sndrName
}
}
}
});
Here is my html code:
<li class="item item-avatar item-icon-left1 item-icon-right" ng-repeat="(id, contact) in contacts" ui-sref="app.chat-single" on-hold="moreOptions('{{id}}')">
<img src="venkman.jpg">
<h2>{{contact.sndrName}}</h2>
<p><span class='margin-l-10'>{{contact.lastMsg}}</span></p>
Problem is
$scope.contacts[7] = {
'lastMsg': message.text,
'sndrName': message.sndrName
}
is adding a new enter to contacts but its not getting render in html
Can you try adding $apply() ?
I was facing the same problem and it resolved mine.
$scope.$apply(function(){
$scope.contacts[7] = {
'lastMsg': message.text,
'sndrName': message.sndrName
}
});
I'm not sure if it's correct but you can give it a try.
use $scope.$apply(); after the loop execution
$rootScope.$on('chat_contact', function(event, data) {
var message = data.message;
if(data.key === 'IM_MSG') {
console.log("chat_contact.........");
var contact = $scope.contacts[message.sndrId];
if(contact) {
contact.lastMsg = message.text;
contact.sndrName = message.sndrName;
} else {
$scope.contacts[7] = {
'lastMsg': message.text,
'sndrName': message.sndrName
}
$scope.$apply();
}
}
});

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?

InfiniteScroll - AngularJS not working

Edit:
Just for checking purposes, I also did a console.log inside the nextPage function, to check if it's being triggered:
$scope.nextPage = function() {
var captureLength = $scope.captures.length;
console.log('TRIGGER');
if($scope.busy) {
return;
}
...
}
};
And it seems I'm getting a infinite loop, but I can't see why.
=================================
I'm trying to implement infinitescroll into a view but for some reason it's only loading the initial 4 images and not triggering the rest.
Here is my code:
CTRL:
/* ----------------------- Variables ----------------------- */
$scope.auth = auth;
$scope.captures = [];
$scope.following = [];
$scope.allData = [];
$scope.busy = true;
var page = 0;
var step = 4;
$scope.nextPage = function() {
var captureLength = $scope.captures.length;
if($scope.busy) {
return;
}
$scope.busy = true;
$scope.captures = $scope.captures.concat($scope.allData.splice(page * step, step));
page++;
$scope.busy = false;
if($scope.captures.length === 0) {
$scope.noMoreData = true;
}
};
/* ----------------------- Process Data ----------------------- */
$q.all({follows: findFollow(), users: getUsers(), captures: getAllCaptures()}).then(function(collections) {
var follows = collections.follows;
var users = collections.users;
var captures = collections.captures;
follows.filter(function(follow) {
return follow.follower_id === auth.profile.user_id;
}).forEach(function(follow) {
users.filter(function(user) {
return user.user_id === follow.followed_id;
}).forEach(function(user) {
$scope.following.push(user);
});
});
follows.filter(function(follow) {
return follow.follower_id === auth.profile.user_id;
}).forEach(function(follow) {
captures.filter(function(capture){
return follow.followed_id === capture.userId;
}).forEach(function(capture){
console.log(capture);
$scope.allData.push(capture);
});
});
$scope.nextPage();
$scope.busy = false;
});
/* ----------------------- Retrieve Services - Data ----------------------- */
function findFollow() {
return userApi.findFollow().then(function(res) {
return res.data;
});
}
function getUsers() {
return userApi.getUsers().then(function(res) {
return res.data.users;
});
}
function getAllCaptures() {
return captureApi.getAllCaptures().then(function(res) {
return res.data;
});
}
Partial:
<div class="col-md-8">
<div class="well main-well">
<h3 class="page-header-h3">Following Dashboard:</h3>
<hr />
<h4 align="center" ng-show="!captures.length">
<strong>The people that you are following, have not posted anything yet.. Yikes!</strong>
<br /><br />
Quickly, go follow more people!</h4>
<div class="row" infinite-scroll="nextPage()" infinite-scroll-disabled="busy || noMoreData" infinite-scroll-distance="0.1">
<ul class="dynamic-grid" angular-grid="captures" ag-id="gallery">
<li data-ng-repeat="capture in captures | orderBy :'created_at':true" class="grid">
<a ui-sref="detail({id: capture._id})">
<img ng-src="{{capture.picture}}" class="grid-img" />
<span class="follow-capture-info">
<span class="follow-capture-name"><span class="glyphicon glyphicon-user"></span>
{{capture.author}}
<span class="following-capture-time">ยท
<span class="glyphicon glyphicon-time"></span>
<span am-time-ago="capture.created_at"></span>
</span>
</span>
</span>
</a>
</li>
</ul>
</div>
<div ng-show="busy">Loading more...</div>
</div>
Anyone know where I went wrong?
Thanks.

Resources