Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

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!