Created
December 5, 2014 01:31
-
-
Save danethurber/54c97ead558567b00550 to your computer and use it in GitHub Desktop.
Angular POJO Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var angular = require('angular'), | |
app = angular.module('app', []); | |
require('./components/user/user-model'); | |
app.controller('UserIndex', ['$scope', 'User', function($scope, User){ | |
$scope.users = []; | |
for (var i = 0; i < 10; i++){ | |
$scope.users.push(User.findOne()); | |
} | |
}]); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var angular = require('angular'), | |
_ = require('underscore'); | |
function User(initialData) { | |
if (initialData) | |
_.extend(this, initialData); | |
} | |
User.$factory = ['$q', '$http', function($q, $http) { | |
_.extend(User, { | |
_q: $q, | |
_http: $http | |
}); | |
return User; | |
}]; | |
angular.module('app').factory('User', User.$factory); | |
User.endpoint = 'http://api.randomuser.me/'; | |
User.findOne = function() { | |
var instance = new User(); | |
User._http.get(User.endpoint) | |
.then(User.parse) | |
.then(function(data){ | |
_.extend(instance, data); | |
}); | |
return instance; | |
}; | |
User.parse = function(res) { | |
var deferred = User._q.defer(); | |
deferred.resolve(res.data.results[0].user); | |
return deferred.promise; | |
}; | |
User.prototype.getName = function() { | |
return (this.name) ? this.name.first + ' ' + this.name.last : ''; | |
}; | |
User.prototype.getAvatar = function() { | |
return (this.picture) ? this.picture.thumbnail : null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment