0

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); 
 }

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.