如何在angularjs中使用ng-repeat显示JSON数组?

时间:2014-11-26 17:44:13

标签: javascript json angularjs

这应该很简单,但我无法解决这个问题,也不知道我哪里出错了。我有一个角度模块,应该重复JSON数组的数据;我的控制器和模块看起来像下面那个

 (function() {

var timeslots = data;

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

app.controller("TimeSlotController", function(timeslots) {

    this.timeslots = JSON.parse(timeslots);

});

})();


 <div ng-app="TimeSlot">
                <div class="col-md-12" ng-controller="TimeSlotController as slot" ng-repeat="item in slot.timeslots" >
                     <div class="col-md-4 timeblock">
                        <h3 class="event-type-name">{{ item.time }} Hour Appointment</h3>
                        <div class="description mts">{{ item.description}}</div>
                        <div class="cost"><i class="fa fa-euro"></i>{{ item.cost }}</div>
                     </div>
                </div>

             </div> 

        </div>

        <!-- jQuery -->
        <script src="http://code.jquery.com/jquery.js"></script>
        <!-- Bootstrap JavaScript -->
        <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            var data = {{{ timeslot }}}     
        </script>
        <script src="/js/timeslot.js"></script>

这是我要解析的数据,

vardata=[
{
    "time": 1,
    "description": "Here lies 1",
    "cost": "10"
},
{
    "time": 2,
    "description": "Here lies 2",
    "cost": "20"
},
{
    "time": 3,
    "description": "Here lies 3",
    "cost": "10"
}

任何帮助将不胜感激,我已经看过其他帖子,我无法弄清楚,所以很抱歉,如果它是一个重复的帖子。

3 个答案:

答案 0 :(得分:2)

data全球?你不能将简单的变量注入你的控制器 尝试从控制器功能中删除参数 也解析已解析数据的原因?

只需将您的数据发送到$scope

app.controller("TimeSlotController", function($scope) {

    $scope.timeslots = timeslots;

});

在控制器视图中使用它:

<div ng-controller="TimeSlotController">
 <div class="col-md-12" ng-repeat="item in timeslots">
    {{item}}
 </div>
</div>

答案 1 :(得分:0)

如果重复控制器,则变量时隙在同一行上不可用 像这样尝试你的HTML:

<div class="col-md-12" ng-controller="TimeSlotController as slot"  >
    <div class="col-md-4 timeblock" ng-repeat="item in slot.timeslots">
        <h3 class="event-type-name">{{ item.time }} Hour Appointment</h3>
        <div class="description mts">{{ item.description}}</div>
            <div class="cost"><i class="fa fa-euro"></i>{{ item.cost }}</div>
    </div>
</div>

答案 2 :(得分:0)

您需要使用$ scope,从控制器到视图和副代的角度绑定数据。

app.controller('TimeSlotController', function ($scope){
    $scope.timeslots =  JSON.parse(timeslots);
});

所以,在你看来,你只需拼写它:

 <div ng-repeat="item in timeslots">

ps:sqs my english