如何在范围变量angularjs中获取json数据

时间:2016-08-10 08:35:50

标签: javascript angularjs arrays json

这是我的Json数据

mytest.address.city // this is working fine
mytest.specialities.name // not printing anything

$ scope.test = data; 我在html中获取数据 ng-repeat =“mytest in test”而不是

{{1}}

我正在面对访问专业名称的问题我认为这是因为专业是阵列但不知道如何获得它。

3 个答案:

答案 0 :(得分:2)

您在

中定义了一个只有一个数组的专业对象

an item with "small weight and benefit" is grouped with another item with "large weight and benefit"

<强>更新

此外,您可能希望确保数组至少包含一个元素,否则您可能需要var Parent = React.createClass({ getDefaultProps: function() { return { ajaxApi: ['foo1','foo2','foo3'] }; }, getInitialState: function(){ return ( { data1: [], data2: [], data3: [] }); }, componentDidMount: function() { Promise.all(this.props.ajaxApi .map(a => { return new Promise((resolve, reject) => { //using superagent here (w/o its promise api), "import request as 'superagent'. You'd import this at the top of your file. request.get(a) .end((error, response) => { if (error) { return resolve(response) } else { resolve() } }) }) ) .then(v => { this.setState({ data1: v[0], data2: v[1], data3: v[2] }) }) .catch(() => { console.error("Error in data retrieval") }) }, render: function(){ return ( <div> <Child1 data={this.state.data1} /> <Child2 data={this.state.data2} /> <Child3 data={this.state.data3} /> </div> ) } })

所以代码应该是这样的:

var Parent = React.createClass({ // these are your api calls getDefaultProps: function() { return { ajaxApi: ['api/call/1','api/call/2','api/call/3'] }; }, getInitialState: function(){ return ( { data1: [], data2: [], data3: [] }); }, fetchApiCallData: function(api) { return axios.get(api); }, componentDidMount: function() { axios.all(this.props.ajaxApi.map(function(api) { fetchApiCallData(api) })).then(axios.spread(function(req1, req2, req3) { // requests complete this.setState({ data1: req1, data2: req2, data3: req3 }) })); }, render: function(){ return ( <div> <Child1 data={this.state.data1} /> <Child2 data={this.state.data2} /> <Child3 data={this.state.data3} /> </div> ) } })

答案 1 :(得分:0)

mytest.specialities 是数组。 JSON有两个可能的选项 [] - 数组, {} - 对象。在这种情况下,我们有对象数组 - [{/ * object data * /}] 所以要获取对象参数首先转到这样的数组元素(例如获取索引0上的第一个元素):

Object

第二个要素:

mytest.specialities[0].name 

每个例子:

mytest.specialities[1].name 

当然在此之前将mytest设置为范围如下:

<div  ng-repeat="special in mytest.specialities">
    <span>{{special.name}}</span>
</div>

答案 2 :(得分:0)

假设有很多专业,你应该使用ng-repeat来显示它们。

$scope.mytest=mytest;//mytest is your data structure