Laravel/Angular: passing data within php page to angularjs

倾然丶 夕夏残阳落幕 提交于 2019-12-06 07:21:27

问题


I have the following laravel html/blade page and i want to pass in a storeid that then can get picked up via angular to then use to get and do some workings with.

Below is how i am accomplishing it NOW but is there a better way to produce the same?

Blade Partial

<div ng-controller="storeChartCtrl" data-storeid="{{ $store['id'] }}">
    <p>{{ $store['name'] }} Sales</p>
    ...
</div>

Angular Ctrl

.controller('storeChartCtrl', ['$scope', 'Store', function($scope, Store){
    //-- get the requested store sales
    var storeid = JQ('#storeChart').data('storeid');

    $log.info(storeid);
    ....

This currently works and i get my storeid value so i can then send to my factory to get the data.


回答1:


When using Angular (or even just jQuery), I thank @JeffreyWay for this package:

https://github.com/laracasts/PHP-Vars-To-Js-Transformer




回答2:


Ultimately, you are rendering an HTML page from the server with certain data embedded; you can either embed data inside your HTML, or you can "render" an object full of data in the page like so:

<?php
$value = "Hello";
$bob = "Bob";

// template code

<script type="text/javascript">
myData = {             // make it global for easy access
    blah: $value,
    alice: $bob
};
</script>
?>

and then in your Angular controller, you access that data in pure JS, without needing to juggle data attributes.

.controller('storeChartCtrl', ['$scope', 'Store', function($scope, Store){
    console.log(myData);
})]);


来源:https://stackoverflow.com/questions/24327547/laravel-angular-passing-data-within-php-page-to-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!