2015-05-30 36 views
0

我想通過一個JSON對象到我的應用程序使用ng-init + stringify但它不起作用我得到一個Lexer錯誤。傳遞JSON對象到ng-init

Lexer Error: Unexpected nextharacter at columns 8-8 [#] in expression [friends=#{JSON.stringify(friends)}].

的Javascript

var friends = [ 
{name:'John', phone:'555-1276'}, 
{name:'Mary', phone:'800-BIG-MARY'}, 
{name:'Mike', phone:'555-4321'}, 
{name:'Adam', phone:'555-5678'}, 
{name:'Julie', phone:'555-8765'}, 
{name:'Juliette', phone:'555-5678'} 
]; 

</script> 

HTML

<div ng-init="friends=#{JSON.stringify(friends)}"></div> 

回答

2

你必須這樣做,在角的方式,則可以使用angularjs的$window訪問JavaScript變量和轉換它到$scope變量在控制器中,並可以訪問它在HTML

拿一個看看你的代碼,我只是修改了一些,使其工作,

<!DOCTYPE html> 
<html ng-app="myApp"> 

<head> 
<script data-require="[email protected]" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script> 
<link rel="stylesheet" href="style.css" /> 
</head> 

<body ng-controller="myController"> 
<h1>Hello Plunker!</h1> 
<script> 
    var friends = [ 
    {name:'John', phone:'555-1276'}, 
    {name:'Mary', phone:'800-BIG-MARY'}, 
    {name:'Mike', phone:'555-4321'}, 
    {name:'Adam', phone:'555-5678'}, 
    {name:'Julie', phone:'555-8765'}, 
    {name:'Juliette', phone:'555-5678'} 
    ]; 

var app = angular.module('myApp', []); 

app.controller('myController', ['$scope', '$window', function($scope, $window) { 
    $scope.friendsInscope = $window.friends; 
}]); 

</script> 
<!--<div ng-init="friends=#{JSON.stringify(friends)}">{{friends}}</div>--> 
<div ng-init="friends=friendsInscope">{{friends|| json}}</div> 
</body> 

</html> 

Working plunker

希望這有助於!

3

你應該嘗試與這些報價:

<div ng-init="friends='#{JSON.stringify(friends)}'"></div> 

我不知道什麼是你的模板引擎,但EJS例如,它會是:

<div ng-init="friends='<%= JSON.stringify(friends) %>'"></div> 

此外,如果你有一些問題用一些簡單或/和雙打引號,你可以用這樣的正則表達式替換它們:

<div ng-init="friends='<%= JSON.stringify(friends).replace(/"/g, "\\\"").replace(/'/g, "\\'") %>'"> 

我不知道這是否是最佳做法,或者不是角度,但由於這一點,我可以共享以前從服務器檢索到的角度的一些數據。這樣我就阻止了Angulars控制器向請求後端的公共API請求許多請求。

而在角度方面,你可以這樣做:$scope.friends = JSON.parse(friends)「暴露」你的JSON。