2017-03-17 58 views
0

我有一個控制器將模型渲染到LARAVEL中的視圖。有沒有辦法在javascript中訪問視圖模型?在JavaScript LARAVEL中訪問模型?

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

回答

0

數據分配到window全局對象,這將使其隨處可見,你可以訪問它來自你的JS文件:

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