laracasts / PHP-Vars-To-Js-Transformer

Transform PHP data to JavaScript.
https://packagist.org/packages/laracasts/utilities
MIT License
2.21k stars 219 forks source link

variable in Javascript is undefined #49

Closed thienvulai closed 9 years ago

thienvulai commented 9 years ago

Hi everyone, im using laravel 5 and angularjs for my project. And i needed to pass value from laravel to angularjs. So i installed PHP-Vars-To-Js-Transformer. it was successful. But i cannot access to Javascript variable in View:

LanguageController.php:

 public function create()
{
    $names = $this->initLang();

    JavaScript::put([
        'foo' => 'bar',
        'langs' => $names,
        'age' => 29
    ]);

    return View::make('NAATIMockTest.Admin.Language.create',compact('names'));
}

my route:

// Route create
Route::get('/Admin/Language/create', 'NAATIMockTest\LanguageController@create');

my View create.blade.php:

     <input type="text" name="search" ng-model="search">
         <select name="Name[]" multiple size="10" >
                 <option value="@{{x}}" ng-repeat="x in langs | filter:search">@{{x}}</option>
        </select><br>

javascript on create.blade.php:

var app = angular.module('myApp', []);
app.controller('langCtrl', ['$scope', '$http', function($scope, $http) {
    console.log(window.foo); // bar
    // console.log(user); // User Obj
    console.log(window.age); // 29
    console.log(window.langs);
}]);

But when i check console: there are three lines undefined. Is there anyone can help.

jamesaspence commented 9 years ago

Having the same issue here.

jamesaspence commented 9 years ago

I figured it out. You need to edit your config/javascript.php file to tell it which view / partial to prepend your variables to. So, I ended up prepending them to my template blade file, and they're always included.

matq007 commented 9 years ago

I had to use dot notation 'bind_js_vars_to_this_view' => 'include.footer' to get it to work :)