Skip to content

Instantly share code, notes, and snippets.

@laradevitt
Created October 15, 2015 18:10
Show Gist options
  • Save laradevitt/7e9b2c1790c628a701fa to your computer and use it in GitHub Desktop.
Save laradevitt/7e9b2c1790c628a701fa to your computer and use it in GitHub Desktop.
Render a nested Drupal menu retrieved via REST API inside an AngularJS app
// Consume a Drupal menu resource provided by Services and Services Menu modules
// and render it in an AngularJS app.
//
// A patch to Services Menu is required, see: https://www.drupal.org/node/2407135
'use strict';
var app = angular.module('app', [
'restangular',
'ngRoute',
'ngSanitize',
]);
app.config(['$routeProvider', 'RestangularProvider', function($routeProvider, RestangularProvider) {
RestangularProvider.setBaseUrl('http://example.com/api/v1/menu/main-menu');
// This response intereceptor allows us to get the json array from inside
// the root object output by services_menu.
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
if (operation === 'getList' && what == 'menu/main-menu') {
extractedData = data.tree;
else {
extractedData = data.data;
}
return extractedData;
});
}]);
app.controller('MenuCtrl', ['$scope', 'Restangular', function ($scope, Restangular) {
$scope.menu = Restangular.all('menu/main-menu').getList().$object;
}]);
<!doctype html>
<html class="no-js" lang="">
<head>
<title>Example</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="app">
<!-- Original source: http://stackoverflow.com/a/24877943/4483099 -->
<script type="text/ng-template" id="menu-renderer">
<a ng-href="{{item.link.path_alias|validate_alias:item.link.href}}">{{item.link.title}}</a>
<ul ng-if="item.link.has_children == '1' && item.children.length > 0" class="list-group">
<li class="list-group-item" ng-repeat="item in item.children" ng-include="'menu-renderer'"></li>
</ul>
</script>
<div ng-controller="MenuCtrl">
<ul class="list-group">
<li class="list-group-item" ng-repeat="item in menu" ng-include="'menu-renderer'"></li>
</ul>
</div>
<div ng-view></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment