简体   繁体   中英

passing data to angular.js from PHP

I have my angular.js app built with a php page that contains a variable that my app needs on load. The angular app on load then uses this variable to fetch more data using a POST. What is the best practice for passing a variable to angular? Also, how can I tell angular to not run the initial controller function until after it has the variable loaded? Thanks in advance.

In your case probably the best way is to write it down with something like this:

<script type="text/javascript">
    var _yourSpecialVar = <?php echo $variable ?>;
</script>

And in Angular:

$window._yourSpecialVar

EDIT:

For example in an Angular controller:

angular.module('app').controller('YourController', ['$scope', '$window', function($scope, $window) {
    $scope.myVar = $window._yourSpecialVar
}]);

Use ng-init to pass data from php to angular. It allows you to evaluate an expression in the current scope.

<div ng-init="<?PHP {name='John'}?>">

This directly goes to the scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM