Wednesday, September 11, 2013

Passing your PHP variables to Angular

New to angular from other JS frameworks and can't figure out how to pass PHP variables to Angular? I hit this when I first started, and Google was of no help.

In General, you want to use AJAX calls to get values from your database to your angular app. But what about user authentication?

<?php
session_start();
if (empty($_SESSION['uname'])){
    header("location:auth/login.php");
}
?>


That's a pretty common piece of code. So, how do you pass the username to your Angular app?

Use ng-init when you set up your controller in the HTML. Use PHP to echo variables to the page.

<div class="container-fluid" ng-controller="appCtrl" 
ng-init="userInit('<?php echo $_SESSION['uname']."', '".$_SESSION['role'] ?>')" >

Now, create a userInit function in your angular controller that will handle the variables:

$scope.userInit = function(uid, role) {
 $scope.user = uid;
 $scope.role = role;
 // Get a list of projects for user
 $scope.projectList($scope.user);
}

And it's that simple!

13 comments:

  1. Thanks:) I was stuck on this for a while.

    ReplyDelete
    Replies
    1. Thanks for your comment... It's nice to know that it's helping someone.

      Delete
  2. Another way is to pass in a global Javascript object as a var between script tags in the web page source (PHP page). and a service/factory picks up this value in the AngularJS space. Saves an HTTP request.

    ReplyDelete
    Replies
    1. this is correct way actually..

      Delete
    2. Do you have an example demonstrating this? Would be much appreciated.

      Delete
  3. Thanks for this.. just as jeremy said "I was stuck on this for a while".. :)

    ReplyDelete
  4. when i am using php tag in html template got error message "parse syntax error"please help me to solve this error

    ReplyDelete
  5. Replies
    1. What's not working about it? Telling me it doesn't work doesn't help me help you.

      Delete
  6. thank you so much bro :)
    Good work

    ReplyDelete
  7. Casino | Online Gaming | Casino Software | drmcd
    Discover the best casino 동두천 출장마사지 software and slots games, bonuses 성남 출장샵 and 하남 출장마사지 more at drmcd. Get casino 구리 출장샵 software 영천 출장마사지 reviews, ratings, promotions, latest bonuses.

    ReplyDelete