Ad

How To Pass A PHP Variable To An AngularJS Config

- 1 answer

Let's say I have a HTML file that has AngularJS loaded in with 'ngRoute'.

Then I'm initialize the app by making an index.php file (I'm not displaying the basic HTML tags + angular JS includes here):

<?php $path = 'www.test.com' ?>

<div ng-app="testApp" ng-init="path='<?php echo $path ?>">
   <div ng-view></div>    
</div>

I'm trying to pass the PHP variable to my AngularJS App Config, by this:

// Module
var test = angular.module('testApp', ['ngRoute']);

// Routes
test.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: $rootScope.path + '/pages/display.htm',
        controller:  'testController'
    }) 
});


// Controllers
test.controller('testController', ['$scope', function($scope) {

}]);

This does not work though because the $rootScope is not definied. Can anyone tell me what am I missing here?

Ad

Answer

Based on comments about wanting to keep php and scripts separate just add a script tag with a variable that you can then access from anywhere in angular

<script>
     var myPathVar = '<?= $someVar; ?>';
</script>

Then you can do anything you want with inside angular such as add it as constant , pass it to $rootScope in your config or whatever

Ad
source: stackoverflow.com
Ad