user2762149
user2762149

Reputation: 159

How do I pass the $user object from drupal to an Angular JS app so angular can use it?

I have a Drupal site with a cutom module that I am using to call an angular app.

here is the module code:

/**
 * Implements hook_menu().
 */
function portfolio_menu() {
  $items = array();

  $items['portfolio'] = array(
    'access arguments' => array('access content'),
    'title' => t('Portfolio'),
    'page callback' => 'portfolio_page', 
  );

  return $items;
}

/**
 * Page callback: Displays Your Application on the page.
 *
 * @see your_application_menu()
 */
function portfolio_page() {
  $path = drupal_get_path('module', 'portfolio');
  drupal_add_js($path . '/lib/angular/angular.js');
  drupal_add_js($path . '/lib/angular/angular-resource.js');
  drupal_add_js($path . '/js/services.js');
  drupal_add_js($path . '/js/app.js');
  drupal_add_js($path . '/js/controllers.js');
  drupal_add_js($path . '/js/filters.js');
  drupal_add_css($path . '/css/app.css');
  drupal_add_css($path . '/css/bootstrap.css');
  return theme('portfolio');
}

function portfolio_theme($existing, $type, $theme, $path) {
  $theme = array();

  $theme['portfolio'] = array(
    'variables' => array(),
    'template' => 'portfolio',  
  );

  return $theme;
}

app.js:

angular.module('portfolio', ['tickerFilters', 'tickerServices']).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
    when('/tickers', {templateUrl:'...portfolio/partials/ticker-list.html',   controller: TickerListCtrl}).
    otherwise({redirectTo: '/tickers'});
}]);

here is the last tpl.php file loaded by drupal:

<div ng-app="portfolio" ng-init="user = <? json_encode($user); ?>">
  <div ng-view></div>
</div>

my question is how do I pass the drupal $user object to angular when i call the app, so that the $user data can be used in the angular app?

Upvotes: 0

Views: 791

Answers (2)

Vlad Moyseenko
Vlad Moyseenko

Reputation: 223

Also you can add $user variable to the Drupal.settings and then use it in angular .config or controller

function portfolio_page() {
  $settings['user'] = $user;
  drupal_add_js(array('portfolio' => $settings), 'setting');

And then use it in angular.config or in controller

angular.module('portfolio', ['tickerFilters', 'tickerServices'])
  .config(['$routeProvider', function($routeProvider) {
    var user = Drupal.settings.portfolio.user;
  }]);

Upvotes: 1

jcubic
jcubic

Reputation: 66590

You don't echo the output of json_encode you need to use <?= and the output of the json_encode contain double quotes so you need to change them to single quote

<?= str_replace('"', "'", json_encode($user)); ?>

Upvotes: 1

Related Questions