Reputation: 417
I have a controller rendering model to the view in LARAVEL. Is there a way to access the view models in javascript?
class MyController extends Controller
{
private arr = ['A','B',C'];
public function index() {
return view('/view_name')->with('data',$this->arr);
}
}
view_name.blade.php :
<html>
<body>
<ul>
@foreach ($data as $datas)
<li> {{ $datas }} </li>
@endforeach
</ul>
<script src="...."></script> // External script link
</body>
</html>
External.js :
$(function() {
// trying to access the model $data from the view.
var values = $datas;
alert(values);
}
Upvotes: 0
Views: 2484
Reputation: 9749
Assign your data into the window
global object which will make it available everywhere and you can access it from your JS file:
<ul>
@foreach ($data as $datas)
<li> {{ $datas }} </li>
@endforeach
</ul>
<script type="text/javascript">
window.data = {!! json_encode($data) !!};
</script>
<script src="...."></script> // External script link
$(function() {
// trying to access the model $data from the view.
var values = window.data;
alert(values);
}
Upvotes: 1