Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of a directive that fetches data via Ajax
angular.module('angular-fb.controllers', [])
.controller('MainController', ['$scope', '$http', function($scope, $http) {
$scope.usernames = [];
$scope.demoUsers = [
"tilley.brandon",
"grockit",
"nodecasts",
"adobe",
"cocacola",
"pepsi"
];
$scope.newUser = "";
$scope.populateUser = function(user) {
$scope.newUser = user;
};
$scope.addUser = function() {
if ($scope.newUser.trim() == "") return;
if ($scope.usernames.indexOf($scope.newUser) != -1) {
$scope.newUser = "";
return;
}
$scope.usernames.unshift($scope.newUser);
$scope.newUser = "";
};
$scope.removeUser = function(idx) {
$scope.usernames.splice(idx, 1);
};
$scope.removeAll = function() {
$scope.usernames = [];
};
}])
angular.module('angular-fb.directives', [])
.directive('userCard', ['graph', '$timeout', function(graph, $timeout) {
return {
templateUrl: 'usercard.htm',
replace: true,
scope: {
username: '=userCard',
close: '&onClose'
},
compile: function compile(tElem, tAttrs, transclude) {
tElem.hide(); // hide element on compile so we can fade in on link
return function postLink(scope, elem, attrs, controller) {
var invalidUserData = {
picture: "http://spartansgym.com/wp-content/uploads/2011/12/wrong-doings1.png",
link: "#",
name: "invalid Facebook user"
};
var update = function(user) {
graph(user).success(function(data) {
userObj = {picture: "https://graph.facebook.com/" + user + "/picture?type=square"};
scope.user = angular.extend(userObj, data);
}).error(function() {
scope.user = invalidUserData;
});
elem.fadeIn('slow');
};
// Update the card every time the username value
// changes. Since we're doing Ajax requests, it would
// be a good idea to debounce the call to `update`.
scope.$watch('username', function(value) {
update(value);
});
// It may be possible to make the fade in (and possibly,
// but would be harder, the fade out) a custom directive,
// so that we don't have to meddle around in the scope.
var oldClose = scope.close;
scope.close = function() {
elem.fadeOut('slow');
$timeout(function() {
oldClose();
}, 600);
};
}
}
};
}])
angular.module('angular-fb.filters', [])
// Capitalize a word
.filter('capitalize', function() {
return function(str) {
if (!str) return "";
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
})
// Trim a string to `amount` characters with an ellipse
.filter('trim', function() {
return function(str, amount) {
if (!str) return "";
if (!amount) amount = 50;
if (str.length <= amount) return str;
return str.substring(0, amount) + "...";
};
})
// Bootstrap the application, specifying dependencies
// on all our sub-modules
angular.module('angular-fb', [
'angular-fb.controllers',
'angular-fb.directives',
'angular-fb.filters',
'angular-fb.services'
])
.config(['$httpProvider', function($httpProvider) {
// Facebook whines when you have X-Requested-With set,
// which is a default in Angular--so let's toss it!
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}])
// Convenience method to get OpenGraph data
angular.module('angular-fb.services', [])
.factory('graph', ['$http', function($http) {
return function(user) {
var graphUrl = "https://graph.facebook.com/" + user;
return $http.get(graphUrl);
};
}]);
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Angular Facebook</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<!-- Application JavaScript -->
<script src="app.controllers.js"></script>
<script src="app.directives.js"></script>
<script src="app.services.js"></script>
<script src="app.filters.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="angular-fb" ng-controller="MainController">
<p>If you don't know any Facebook user IDs, try some of these:</p>
<ul>
<li ng-repeat="user in demoUsers">
<a ng-href="#" ng-click="populateUser(user)">{{user}}</a>
</li>
</ul>
<form ng-submit="addUser()">
<input type="text" ng-model="newUser">
<input type="submit" value="Add User">
</form>
<p ng-show="usernames.length">
<a href="#" ng-click="removeAll()">Close All</a>
</p>
<!-- user-card is a custom directive -->
<div ng-repeat="user in usernames" user-card="user" on-close="removeUser($index)"></div>
</body>
</html>
body {
font-family: 'Arial, sans-serif';
}
.usercard {
border: 1px solid black;
margin: 10px 0;
padding: 5px;
width: 350px;
position: relative;
}
.usercard img {
vertical-align: top;
height: 75px;
width: 75px;
}
.usercard .data {
display: inline-block;
width: 250px;
margin-left: 10px
}
.usercard .close {
position: absolute;
top: 3px;
right: 3px;
}
<div class='usercard'>
<span class='close'>
<a href="#" ng-click="close()">x</a>
</span>
<img ng-src="{{user.picture}}">
<div class='data'>
<div class='usercard-name'>
<a ng-href="{{user.link}}" target="_blank">{{user.name}}</a>
</div>
<div ng-show="user.gender">{{user.gender | capitalize}}</div>
<div ng-show="user.about">{{user.about | trim:100}}</div>
</div>
</div>
@BinaryMuse

This comment has been minimized.

Show comment
Hide comment
@BinaryMuse

BinaryMuse Nov 4, 2012

This is an Angular.js application that demonstrates a custom directive, which fires off Ajax requests via the $http service. Run it from the root of any web server and visit index.html in your browser. Here's a Python one-liner for firing up a web server in your current directory:

python -m SimpleHTTPServer
Owner

BinaryMuse commented Nov 4, 2012

This is an Angular.js application that demonstrates a custom directive, which fires off Ajax requests via the $http service. Run it from the root of any web server and visit index.html in your browser. Here's a Python one-liner for firing up a web server in your current directory:

python -m SimpleHTTPServer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment