Radical_Activity
Radical_Activity

Reputation: 2738

How to pass a PHP variable to an AngularJS config

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?

Upvotes: 0

Views: 2462

Answers (3)

charlietfl
charlietfl

Reputation: 171690

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

Upvotes: 3

mzulch
mzulch

Reputation: 1539

You can define a constant in a script tag in the page generated with PHP:

<script type="text/javascript">
    angular.module('testApp').constant('path', '<?php echo $path ?>');
</script>

And in your app config:

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

If path contains any user-supplied content, make sure to escape it appropriately for echoing as a javascript string.

Upvotes: 3

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21671

you might want do do this instead

// Controllers
test.controller('testController', ['<?php echo $scope; ?>', function($scope) {

}]);

I dont use angularJs, but regardless '$scope' would literately be the word $scope

Upvotes: -1

Related Questions