Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I'm getting back into web design after a 7-8 year hiatus. My god, I knew things had changed but after reading the OP and talking to a couple friends it's obvious that I'm going to have to toss out all of my old knowledge and start over. Frameworks, CSS preprocessors, HTML5, grid-based layouts...I feel like I'm in way over my head.

How do I pick one framework over another if I don't have any experience with any of them? I checked out some reviews of PHP-based ones and plan on giving Yii a try, but then someone introduced me to AngularJS and React and now it feels like I could spends months considering my alternatives and still not be able to decide. Should I just pick popular frameworks and learn them? Are frameworks mutually exclusive - would I use AngularJS with Laravel, for example?

Edit: I should mention that I'm comfortable with HTML/CSS/JS/PHP/etc... but I've never used a framework before and the last time I did any development it was alright to render pages on the server. I'm now coming to understand that RESTful APIs are now king, and that client-side frameworks are designed to pull content from server-side frameworks that expose the API.

IAmKale fucked around with this message at 02:47 on Jan 24, 2015

Adbot
ADBOT LOVES YOU

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I just found out recently that Github has a system in place to host static websites for free. I've been paying for personal hosting for years but since I've just been using it recently to host a static personal page I'm thinking of moving my domains over to Google Domains and switching the couple of static sites I have over to the Github pages system.

If I were to do that, though, what would be my best option for temporary web-facing server access? For example, if I develop a dynamic website locally and want to show it off to someone, should I just spin up an Azure or AWS LAMP instance and pay for however long I need it up to show off my work? Since REST is king is there some kind of website or service I can use if all I want to do is set up a DB to store data and process API calls? This scenario has been the main reason I've kept my hosting around but if I can find a way to gain server functionality only when I need it for less than $60/yr then I'll be a happy camper.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

revmoo posted:

Check out Sagonet. I pay 30 bucks a month for a dedicated server. Had it for a couple years now and downtimes have been pretty minimal.
I've been paying $5/mo for shared hosting, switching to a dedicated server is the opposite of what I'm hoping to achieve :v:

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

kedo posted:

Yeah, it's maybe a half step better than Geocities was. I see designers apply for jobs with Wix portfolios on occasion and they're painful to look at and use.
I can confirm this. I recently had to fix up our startup's homepage and my boss made me continue to use Wix because he renewed for a year back in November. You can't imagine how long it took me to make a multilingual, single-page homepage while keeping everything synced up design-wise when I needed to move something around :suicide:

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I have an odd question about hrefs to CSS files with respect to AngularJS, .htaccess, and a bookmarked route.

While trying to figure out how to get rid of index.html in Angular URLs I discovered Angular's html5mode. After enabling this I discovered that going directly to a route (i.e. http://myapp.com/event/1) returns a 404 because the server doesn't know to return index.html for all requests. This led me to the following .htaccess file:

code:
RewriteEngine on
#let angular do its thing
RewriteCond %{REQUEST_FILENAME} !-f      
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.html [NC,L]
With this in place I'm now able to go directly to http://myapp.com/event/1 and it loads up fine.

However! Something strange happens with these direct links: namely, my index.html's stylesheet won't load if don't include a forward slash at the beginning of the href:

HTML code:
<!-- CSS won't load when directly linking to an event -->
<link href="css/main.css" rel="stylesheet" />
But if I throw in a preceding forward slash, it loads fine:

HTML code:
<!-- This loads fine -->
<link href="/css/main.css" rel="stylesheet" />
Even stranger, if I load up index.html like normal and then click the link that takes me to /event/1 everything looks fine even if I don't have the preceding forward slash. It's only when I directly link to /event/1 that the stylesheet fails to load. AND I didn't have to edit any of my other href's or src's, just the one CSS declaration in the head. Is something wrong with my .htaccess file?

You can see the weird behavior here (I've taken out the preceding forward slash in the code):

https://calendar-angularjs-masterkale1.c9.io/ > click an event, everything looks fine

vs

https://calendar-angularjs-masterkale1.c9.io/event/1

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Alright, so it's just a matter of relative versus absolute paths. I probably would have experienced similar issues with JavaScript files not using absolute paths if I had anything on /event/ that Angular needed to respond to. I guess that's one of the benefits of single page apps - everything can be linked from an absolute path since index.html powers everything.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

v1nce posted:

You would have probably seen this if you checked dev-tools while still using the relative paths - namely a 404 for the CSS files at "/youre/doing/it/wrong/css/main.css".
Actually I took a look again this morning and there's still one confusing bit about all of this: the header calendar image uses a relative link but loads up fine when you directly access /event/1. Why does that link work but the CSS one has issues? It's not a problem at all to change all of these into absolute links but the fact that some resources load fine with relative links while others need to be changed to absolute links. Maybe it's a distinction between what's in the <head> and what's in the <body>...

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

v1nce posted:

That shouldn't make any difference. How is this image defined? Can you show me the code?
Here's some HTML as appears when accessing https://calendar-angularjs-masterkale1.c9.io/event/1 (I reverted the code for the same of troubleshooting):
code:
<html>
  <head>
    <link href="https://s3.amazonaws.com/codecademy-content/projects/bootstrap.min.css" rel="stylesheet" />
    <!-- This <link> won't load... -->
    <link href="css/main.css" rel="stylesheet" />
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
    <script src="https://code.angularjs.org/1.2.28/angular-route.min.js"></script>
    <base href="/">
  </head>
  <body ng-app="CalendarApp">
    <div class="header">
      <div class="container">
        <!-- ...but this <img> will -->        
        <a href="/"><img src= "img/logo.svg" width="51" height="54"></a>
EDIT: I removed the preceding slash from <img>

IAmKale fucked around with this message at 07:43 on Feb 4, 2015

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

down with slavery posted:

The logo path is an absolute path. It starts with /

That's what you want the css link to look like as well
Ugh, I forgot to remove that forward-slash - that wasn't in the original HTML file. I inserted it yesterday during testing but forgot to remove it before I posted it. Try the link now, I removed the preceding slash yet the <img> displays just fine.

IAmKale fucked around with this message at 07:45 on Feb 4, 2015

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

ynohtna posted:

You have <base href="/"> in your head so all relative paths are relative to site root. It doesn't affect your CSS declaration which comes before it.
Well I'll be, that was it. I also discovered that moving <base> above the CSS declaration "fixed" the relative CSS declaration as well. Thanks for pointing that out.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Are there any database hosting services that will help me to quickly get an API service up and running for cheap/free? I want to start practicing development with AngularJS but I'm feeling overwhelmed since I also feel like I have to simultaneously learn something like the Django REST Framework first before I can proceed. I'm just looking for something I can use in development to auth against and store data. Once I get comfortable with the Angular I figure I can then move on to Django and learn that at my leisure.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Cross-posting from the Front-end Developers thread, can anyone give me some advice on how I might improve my Firebase Auth service to better convey error messages to AuthController? The tutorial I was working through uses an older version of the AngularFire so I had to update the code to work with the new authentication API calls. I'm having an issue where errors are caught in the Service, so the Controller has no idea that anything's gone wrong unless I check for an error every time the function is called.

Here's the start of my Auth service:
code:
app.factory('Auth', ["$firebaseAuth", "FIREBASE_URL", "$rootScope", function($firebaseAuth, FIREBASE_URL, $rootScope) {
	var ref = new Firebase(FIREBASE_URL);
	var auth = $firebaseAuth(ref);

	var Auth = {
		register: function(user) {
			return auth.$createUser({email: user.email, password: user.password})
				.then(function(userData) { Auth.error = ''; })
				.catch(function(error) { Auth.error = error.message; console.log('Authentication failed:', error); });
		},
And here's how I'm checking for errors from within my AuthController:
code:
// Register the user with Firebase, then login as the user, then
// redirect them to the main page
$scope.register = function() {
	Auth.register($scope.user).then(function() {
		if(Auth.error) {
			$scope.error = Auth.error
		}
		else {
			return Auth.login($scope.user).then(function() {
				if(Auth.signedIn()) {
					console.log('Redirecting to main page');
					$location.path('/');
				}
				else {
					$scope.error = Auth.error;
				}
			});
		}
	});
};
The end goal is populating this simple <p> element with the error message:
code:
<p ng-show="error" class="text-danger">{{ error }}</p>
Right now everything works fine but I'm getting the feeling that there's a better way to do this.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Is there any recommended reading on how best to store/structure data in a NoSQL database? I'm pretty comfortable with SQL and relational databases but NoSQL is like the wild west to me. For example, foreign keys don't appear to really be a thing so it seems easy to inadvertently end up with duplicated data all over the place.

Edit:

v1nce posted:

If you still want Auth.error to be present, then there's no problem in keeping that around in the service for other things to access if they're interested (think of it as "lastErrorThatOccurred"). But if you can deal with the promises directly and capture the errors usefully, there's no reason to keep it around.
Thanks for emphasizing the fact that I'm getting back a promise whenever I register/log in a user. It's way easier (and cleaner) for me to just return the promise from the Service and let my Controller handle it, as you suggested.

IAmKale fucked around with this message at 18:58 on Feb 10, 2015

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

revmoo posted:

The whole point (correct me if I'm wrong pls) of a nosql db is that there is no relational data. You're either storing high-performance key/value data or unstructured documents. If you need relations you use something else. As far as I know the only way to get something like foreign keys to work would be in your application database wrapper. Which seems fine to me--keep your rdbms and key it in software to whatever nosql solution you need for that portion of your data. We actually do this at work to coorelate memcached values to data in our Postgres DB.
Foreign keys were just an example of a difference between the two. I'm more interested in reading up on best practices for modeling data in a NoSQL-friendly way.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
How can I copy to the clipboard the JSON object representing my Firebase auth object? I've been console.log()'ing it so I can see it in Chrome's Developer Tools but I need to see the whole thing in straight JSON format so I can figure out why my Firebase security rule isn't working.

Edit: is there an IRC channel for web dev?

IAmKale fucked around with this message at 02:43 on Feb 24, 2015

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I tried that, it choked on "circular object". I found what I needed under the Resource tab > Local Storage, though.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I've come across what I think is an async-promises related issue in an Angular app I'm playing with. I'm currently using AngularFire to handle logins with Firebase. I have a NavController that controls stuff in the site's navigation bar. Since the site is pretty barebones at this point I just have a basic template that shows the site's name as well as a logout link when the user is logged in:

code:
<div class="header" ng-controller="NavController">
	<div class="pull-right">
		<span ng-show="username">{{ username }}</span>
		<a href="" ng-click="logout()" ng-show="isSignedIn()">Log Out</a>
	</div>
	<h2><a ng-href="/#/">{{ "app_name" | i18next }}</a></h2>
</div>
And here's NavController:

code:
'use strict';

app.controller('NavController', ["$scope", "$window", "Auth", 
	function($scope, $window, Auth) {

	$scope.isSignedIn = Auth.isSignedIn;
	if($scope.isSignedIn()) {
		console.log("Assigning username", Auth.user.profile.username);
		$scope.username = Auth.user.profile.username;
	}

	$scope.logout = function() {
		Auth.logout();
		//console.log("setting path to /login");
		$window.location.reload();
	};
}]);
Everything works fine except the assigning of the username. The console output shows "Assisning username: undefined". However, if I change the console to log Auth.user, I see the entire JSON string along with the profile child and the exepcted username value. Strangely enough, the logout link shows up fine.

The reason I think this is an async issue is because I make a second async call to grab the user's profile from Firebase after I get back the authData object. I then add the results of that second call to authData so I have user profile information available wherever I need it. What I'm thinking is happening is that I'm getting back the initial auth payload which has enough info to determine if the user is logged in, but the username assignment happens before that second async call finishes so nothing can be assigned. What can I do to get this to work? I know about resolving things in the router, but I'm not sure if there's anything similar for controllers.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Hey guys, am I opening myself up to anything if I use a Firebase with read/write rules set to False at the top most level, and then authenticate as an admin in a Python script that's intended to interact with the database? As in, is that a bad habit to get into? I'll eventually open it up for reads from Angular but for now it'll just be a means of storing and retrieving API keys for another service.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Is ng-book still the go-to reference book for people who want some Angular-oriented literature to read? I was all eager to buy it until I saw the reviews on Amazon - a fair amount basically say this is the Angular API copy-pasted into book format with lovely editing and organization of the content surrounding the examples.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

Hed posted:

I personally got far more out of the Orielly one. Each has a very small half-life with Angular 2 on the horizon imo, but I'm lazy.
I'm starting a project soon which means we'll probably lock down Angular to 1.3.15 since it's the current stable release. And 2.0's eventual release won't necessarily mean that demand for the older versions will immediately dry up. I get your point, though, and that was one of the reasons I wanted to get ng-book: they promise free content updates with their ebook packages, so I'm hoping that that might include updates in the future to cover stuff specific to 2.0...

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
edit: poo poo, I keep forgetting about the Django thread

IAmKale fucked around with this message at 23:56 on Apr 13, 2015

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I'm working on my first API right now (using Django Rest Framework) and I have a general question about crafting a usable API. First off, I'm trying to make this API for a webapp that could potentially be used by employees from multiple companies. Obviously I need to set up permissions to prevent employees from Company A from modifying entries for Company B.

Right now I've been working with verbose routes like /companies/1/locations/2/requests. However, I realized this morning I could simplify things and just make a basic /requests/ route and then use the employee's token (that they're submitting for authentication) to look up the employee's company and/or location. The simpler route would also make it easier for SPA's to interact with the API as no one would have to know what company or location an employee is when CRUD'ing requests. Is this a good design decision?

IAmKale fucked around with this message at 18:50 on Apr 16, 2015

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
What's the best Angular-centric way of storing an auth token for API calls? I have an API up and running and handling logins, but now I need to write up a service to handle logging in and verifying the token is available. Should I just use plain HTML5 localstorage?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I'm writing my first serious Angular SPA using the NGBoilerplate style as the foundation and I need help figuring out how to access constants defined in one module from another module. Basically, I want to access the USER_ROLES constant defined in my main module from another module.

Here's my main module
code:
(function() {
	'use strict';

	angular.module('webapp-client', [...snip...])

	.constant('USER_ROLES', {
		admin: 'admin',
		manager: 'manager',
		employee: 'employee'
	})
And here's the homepage module:
code:
angular.module( 'webapp-home', [
	'ui.router'
])

.config(function config( $stateProvider, USER_ROLES ) {
	$stateProvider.state( 'home', {
		url: '/home',
		views: {
			"main": {
				controller: 'HomeCtrl',
				templateUrl: 'home/home.tpl.html'
			}
		},
		data:{
			pageTitle: 'Home',
			authorizedRoles: [USER_ROLES.admin, USER_ROLES.manager, USER_ROLES.employee]
		}
	});
})
When Grunt tried to build the site it spit back an error saying:

quote:

Error: [$injector:unpr] Unknown provider: USER_ROLES

Then I tried adding USER_ROLES followed by webapp-client.USER_ROLES into webapp-home's dependencies when I declared the module but those just produced similar errors:

quote:

Error: [$injector:nomod] Module 'USER_ROLES' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I thought it would be as easy as passing in dependencies into a Controller but it turns out it isn't quite so simple. What am I doing wrong?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

Silvah posted:

The problem is you're trying to access a link-time constant at compile-time (the config method happens before linking). What you're looking for instead of data is "resolve": https://github.com/angular-ui/ui-router/wiki#resolve
Thanks for the tip, that makes sense and worked perfectly when I tweaked my code.

On a related note, is there a better way of including authenticated/authorization checks than to include this block of code at the top of every controller?
code:
if(!AuthService.isAuthenticated()) {
	$rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
	return;
}
else if(!AuthService.isAuthorized(authorizedRoles)) {
	$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
	return;
}
Edit: Nevermind, it appeared to be a problem with my machine.

IAmKale fucked around with this message at 01:02 on May 11, 2015

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

Silvah posted:

If you want to avoid putting that block in every controller, you're probably better off overall just using strings and the data declarations in your states, rather than trying to inject the USER_ROLES constants at link-time.
I guess I should just stick with declaring strings in data{}, it seems a lot easier than trying to hack my way around the fact that there's no good way to load up constants before loading a state. I'd tried that earlier and had it working while I was looking around for a solution, but the constants line up with the structure of my API so I figured it'd be a good idea to create a constant to make sure the two sync up.

Now I have a Bootstrap problem. I'm creating a user portal that will hide some options based on the user's current role. I'm using this basic layout right now to present two options per row, up to however many options might be made available in the future:

code:
<div class="container portal-options">
	<div class="col-md-6">
		<a ui-sref="base.foo">
			<button class="btn btn-lg btn-primary menu-nav-button">
				<i class="fa fa-clock-o"></i>
				<p>Option1</p>
			</button>
		</a>
	</div>
	<div class="col-md-6" ng-show="isAuthorized(['admin', 'manager'])">
		<button class="btn btn-lg btn-primary menu-nav-button">
			<i class="fa fa-users"></i>
			<p>Option2</p>
		</button>
	</div>
</div>
Unfortunately, if the Option2 is hidden because the user isn't authorized, the first item still sits off to the side instead of (ideally) expanding to fill up the whole space. Is there anything I can study up on that will help me figure out how to get the first column to expand into the entire available space if the second option is hidden? Should I just switch out classes if the auth check fails?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I have two ng-repeats, one nested inside the other. How can I get the parent ng-repeat's $index from within the child ng-repeat?

code:
<div class="container">
    <div ng-repeat="location in ctrl.locations">
        <!-- CONTENT GOES HERE -->
        <div class="shiftee-settings-row" ng-repeat="station in location.stations">
            <!-- There doesn't appear to be a way to grab the location's index from here... -->
            <button type="button"ng-click="ctrl.updateStation(location.$index, station)">Update</button>
        </div>
    </div>
</div>
I want to refresh only the affected location's list of stations, and to do that I need the location's index within ctrl.locations. Nothing within a location object indicates its position in ctrl.locations, though, and unfortunately $index isn't available within the location object. If it's not possible I might have to A) maintain a reverse array mapping location.id's to indices, or B) just refresh the whole page. B's kinda wasteful, though, and could potentially hammer the API server with requests if abused/the list of locations grows larger.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

gmq posted:

I can't test right now but I think $parent.index would give you the index you want.
Thanks for pointing out $parent, I think that put me on the right track. Is it normal, though, to have to use $parent.$parent.$index? $parent.$index is the same as the $index of the current station I'm manipulating. $parent.$parent.$index does give me the desired number, but it feels strange that I have to go that one extra level deep.

Edit: I found this SO post that explains a couple of different ways to handle this: http://stackoverflow.com/questions/14807258/access-index-of-the-parent-ng-repeat-from-child-ng-repeat. The cleanest looks to be defining a variable for the key in the parent ng-repeat for ease-of-access in descendant ng-repeats.

IAmKale fucked around with this message at 20:59 on May 14, 2015

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
What are some good services for sending notifications to users via email or SMS? Everything seems to be focused on sending out mobile device notifications but I need something a bit more traditional for this web app I'm working on. Amazon has its "SNS" service but I've just started reading the API docs and so I'm not yet sure if it's a feasible solution.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Moment.js is tripping me out with some functionality that runs counter to my experiences with Objects in Javascript. When I grab a duration and output it to the console:
code:
var duration = moment.duration(end-start);
console.log('duration:', duration);
I get what looks like a regular Object:


But when I try to access, say, duration.data.hours Chrome spits out an error, "TypeError: Cannot read property 'data' of undefined". Of course, this is not the proper way to access hours according to the Moment docs - I'm supposed to retrieve it with duration.hours() (and indeed that does work). It's weird, though, that I still get back what looks like a regular object when I write it to the console. And yet I can't access any of its parameters as with other "typical" (?) Objects.

What's going on here? How did they accomplish this?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

butt dickus posted:

It's a private object property.
Oh, so private object properties will show up like normal Object properties in the console? Interesting. Is there a way to tell whether an object property is private or not based solely on console output?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Thanks for the link, now it makes more sense.

Now I've another question, this one related to Angular. Let's say I'm iterating through items and displaying the total number of hours of those items as such:
code:
<td
    ng-repeat="day in ctrl.dayNumbers"
    ng-class="{danger: THIS.value < ctrl.someNumber }">
        {{ ctrl.calculateColTotalHours(ctrl.items, $index) | asHrsMin }}
</td>
Is it possible to get the value of the <td> after the binding is calculated and use it to apply the style "danger" as per my pseudocode?

And I just realized that the filter will probably complicate things. I thought about calculating the total hours via ng-init but that won't update the value as items are added to or removed from ctrl.items...

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I just figured out AWS' SES service for sending out e-mails via SMTP in Python, so now I need to figure out how to expose this new "send an e-mail" functionality to the clientside of things in a REST-oriented way.

Right now I'm thinking about making an endpoint, something like /v1/api/admins/send_notification/<template ID>. The idea is, there are three different types of notices to send out, and the client just needs to specify which notice (template) to use. Provided the POST call passes authentication and authorization, the server would then handle preparing and sending out e-mails based on the specified template as it's defined on the server. Afterwards it'll probably return the number of e-mails sent, or some other kind of object of success:failure messages indicating that SOMETHING happened.

Is there a better way of going about this?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I'm having the most bizarre issue with an Angular ngRepeat. I have four records stored in a database that I retrieve via a REST call and then process in JavaScript. The resulting object looks like this:

JavaScript code:
vm.templates = {
    9: { id: 9, title: 'AM' },
    10: { id: 10, title: 'PM' },
    11: { id: 11, title: 'Any' },
    12: { id: 12, title: 'Off' }
}
I then display all of these using a basic ngRepeat:
code:
<button ng-repeat="template in ctrl.templates">
I want these items to display in this exact order, so I only need a basic ng-repeat. The problem I'm having is that these buttons are completely out of order only when hosted on Heroku.

When I run the code locally, this is the (correct) order that's displayed:


But when I upload and run the code on Heroku the order is completely bonkers:


I tried explicitly sorting by id but that didn't help:
code:
<button ng-repeat="template in ctrl.templates | orderBy:'id'"
Just to be sure I dove into the (PostgreSQL) database and looked at the ordering of the records in the database. While not visually displayed in the correct order, the IDs are in the proper sequential order:


So what the hell is going on? I just started running into this problem and some console logging confirms that the order of the object is exactly the same regardless of whether it's output locally or when hosted online. It's just the ng-repeat that fucks up the order.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

bartkusa posted:

Object keys don't have an order.

Arrays have an order. Maybe you can pull out the keys of the object into an array, sort them, iterate over them, and use each one to do a value lookup.
Okay, so this is related to the fact that objects don't maintain an order. Then it's just a fluke that things are displayed in proper order on my local machine?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

EmmyOk posted:

Checking if they have unlocked a lesson is simple I am just not sure if hiding list elements can be done in PHP.

As I wasn't sure if this type of thing will involve JavaScript, HTML, or PHP I posted it here instead of the PHP questions thread.
Are you rendering the page on the server and feeding back HTML? If that's the case, then when you get to the for loop that creates the various list items add a if(lesson.id <= student.current_lesson_id) or if(in_array(lesson.id, student.completed_lessons)) (pseudocode) check. This'd prevent anything past the student's current lesson from being rendered to the page.

Edit: You mentioned you can already check for which lessons have been unlocked.

IAmKale fucked around with this message at 22:32 on Jul 20, 2015

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

EmmyOk posted:

The way they have it laid out is just a list of links on the homepage.

code:
<div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation">
        <div class="list-group">
          <a href="mathsOp.php" class="list-group-item">Maths Operations</a>
              .
              .
              .
          </div>
</div>
I do have a table in my database looking after what lessons each user has unlocked. When they click on a lesson in that list the page checks if they have unlocked that page, if they haven't it redirects them.
So that homepage is just a static HTML file? Are you using a framework for the front end? Without knowing more about your setup I can only speak to a general workflow of how you'd handle this from the frontend:

1. Use JQuery to GET from the server the user's list of unlocked lessons
2. Edit the above HTML file and assign an ID to each lesson <a> element that corresponds with the lesson ID you track unlocked lessons by
3. Use JQuery to grab each <a> element and hide it if its ID is not in the list of ID's returned in Step 1

Since there's no server-side rendering going on then you'll need to grab the info from the server and do all the hiding on the front-end. It's not nearly as clean and you're getting into REST authentication but maybe you already have that stuff in place.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

EmmyOk posted:

They've used bootstrap! By the server in part 1 do you just mean the database?
Bootstrap is a UI framework, it greatly simplifies the task of styling things so they don't look like garbage. Since that's all it does, you need to use something like Jquery to perform actual logic-based operations in the browser.

For simplicty's sake, look into getting access to the FTP server and turning that one file you're working on into a PHP file. Then, perform your logic in PHP and then return an HTML page that only displays the user's accessible lesson <a> elements (querying the database for completed lessons is MUCH easier from the server side of things). This'll be a great introduction to serverside-rendering if you're not already comfortable with it.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

Fluue posted:

The reason I ask is because I don't want to setup conditional authentication for mobile/desktop platforms. I'm having trouble wrapping my head around any way to use tokens without duplicating a lot of code/routes.
You can still use token auth on the desktop! The trick is to save the token to a cookie that has an expiration date set in the past so that the cookie only exists while the browser session is active. I was inadvertently doing that for the longest time using ngCookies in Angular 1.3 - I found out the hard way that there's no way to set an expiration date on cookies created with this library so nothing persisted once I closed the browser. Regardless of which library you use for handling cookies (I'm now using angular-cookie), the most you'd have to do is add some code in to check whether the user is on desktop or on mobile and set the cookie's expiration date accordingly.

Setting something like this up in your Angular's app.js helps immensely with simplifying calls to APIs that use token auth:
code:
// Include the required auth token on each $http request
$injector.get('$http').defaults.transformRequest = function(data, headersGetter) {
    var token = ipCookie('token');
    if(token) {
        headersGetter()['Authorization'] = 'Token ' + token;
    }
    if(data) {
        return angular.toJson(data);
    }
};

IAmKale fucked around with this message at 19:26 on Jul 23, 2015

Adbot
ADBOT LOVES YOU

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Hey, are any of you guys dabbling/working in Polymer? I'm just starting out and I'm having a hell of a time getting app-router and more-routing working with 1.0. I want to use something more declarative to define routes but no mater what I tried I just couldn't get either of those to A) display the default path on initial load, or B) actually load a route when I clicked on a link.

I'm very aware of the fact that I'm probably doing something wrong and I plan on starting over with a blank HTML document (I tried modifying the default index.html provided in the Polymer Starter Kit). I'm asking around to make sure there aren't some known issues that I'm fighting against and should just go with Page.js until the other two get sorted out.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply