为什么ng-repeat工作不正常?

时间:2016-08-15 07:28:41

标签: angularjs angularjs-directive angularjs-scope

我使用ng-repeat循环数组,但它只显示{{ }}中的内容。

控制台中没有任何错误,但显示不正确... 这是代码

    <html ng-app="mittens">
    <head>
        <title>Mittens</title>
        <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
        <script type="text/javascript" href="angular.min.js"></script>
        <script type="text/javascript" href="mittens.js"></script>

    </head>
    <body ng-controller="mittensController">
        <div class="container">

            <h3 ng-repeat="meow in meows">{{meow}}</h3>

        </div>
</body>

这是mittens.js文件..

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

    app.controller('mittensController',function($scope){

        $scope.meows = [{
            'This is first sentence',
            'This is second sentence',
            'This is third sentence',
            'This is fourth sentence'
        }];

    });

2 个答案:

答案 0 :(得分:1)

实际上,mittens.js的引用链接被错误地加载了。您应该使用src代替href

HTML:

<html ng-app="mittens">
    <head>
        <title>Mittens</title>
        <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
        <script type="text/javascript" href="angular.min.js"></script>
        <script src="mittens.js"></script>

    </head>
    <body ng-controller="mittensController">
        <div class="container">

            <h3 ng-repeat="meow in meows">{{meow}}</h3>
        </div>
</body> 

脚本:

    var app = angular.module('mittens',[]);
            app.controller('mittensController',function($scope){

                $scope.meows = [
                    'This is first sentence',
                    'This is second sentence',
                    'This is third sentence',
                    'This is fourth sentence'
                ]; //removed {} braces
            });

更新:如果你想参考,这里是Plunker link

答案 1 :(得分:1)

ng-repeat指令适用于数组或对象,但您正在尝试处理只有一个对象的数组,该对象也定义不正确。

Javascript对象的定义如下:{foo: 'Some bar', bar: 'Some foo'}

因此,请尝试在下面的代码中更改代码:

&#13;
&#13;
var app = angular.module('mittens', []);

app.controller('mittensController', function($scope) {

  $scope.meows = [    // <<< remove bracket from here
    'This is first sentence',
    'This is second sentence',
    'This is third sentence',
    'This is fourth sentence'
  ];   // <<< also remove from here

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mittens" ng-controller="mittensController">
  <div class="container">

    <h3 ng-repeat="meow in meows">{{meow}}</h3>

  </div>
</div>
&#13;
&#13;
&#13;