简体   繁体   中英

How to read JSON inside script tag on Laravel + AngularJs

I'm confused that it failed to use JSON on Angular + Laravel(5.2.11)

My plan is,
1. Convey JSON to a blade file
2. Get JSON inside script tag, and set it to a variable
3. Display each data

I added interpolateProvider to avoid duplicating Laravel and Angular description. But actual displayed data is

I checked the following was display I expected.

var json = {!! $contents !!};  

Controller.php

public function show()
{
    $champions = DB::table('Champion')
        ->select('ChampionName', 'ChampionKey')
        ->orderBy('ChampionKey')
        ->get();

    return view('allChampionsPage')->with('contents', json_encode($champions));
}

allChampionsPage.blade.php

@extends('layouts.defaultAngular')

@section('menuItem1', 'When buy')
@section('menuItem2', 'When killed')
@section('menuItem3', 'Where lane')
@section('menuItem4', 'How many CS')
@section('menuItem5', 'Search')

defaultAngular.blade.php

<!DOCTYPE html>
<html lang="ja" ng-app="itemBuildStatisticsApp">
<head>
  <link rel="stylesheet" href="{{{asset('/css/bootstrap.css')}}}" type="text/css">
  <link rel="stylesheet" href="{{{asset('/css/default.css')}}}" type="text/css">
</head>

<body ng-controller="ChampionsController as ChampionsCtrl">
  <?php include_once("analytics/analyticstracking.php") ?>
  <div id="container">

    <div id="header" class="middleContentItem"></div>

    <div id="middle">
      <div id="menu" class="middleContentItem"></div>

      <div id="contents" class="middleContentItem">
        <ul ng-repeat="champion in ChampionsCtrl.champions">
          <% champion.ChampionKey + ', ' + champion.ChampionName %>
        </ul>
      </div>
    </div>

    <div id="right"></div>

    <div id="footer" class="middleContentItem"></div>
  </div>

  <script type="text/javascript">
    var json = {!! $contents !!};

    var app = angular.module('itemBuildStatisticsApp', [], funtion($interpolateProvider){
      $interpolateProvider.startSymbol('<%');
      $interpolateProvider.endSymbol('%>');
    });

    app.controller('ChampionsController', function(){
      this.champions = json.query();
    });
  </script>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
</body>
</html>

Modified code

  <script type="text/javascript">
var json = {!! $contents !!};

var app = angular.module('itemBuildStatisticsApp', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});

app.controller('ChampionsController', function(){
  this.champions = angular.fromJson(json);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM