双重重复呼叫

时间:2014-10-29 11:36:35

标签: javascript angularjs angularjs-ng-repeat

我是AngularJS的新手。也许我的问题会很愚蠢。请提前。

我有index.html:

<html>
<head>
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="bower_components/angular/angular-csp.css">

    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/app.js"></script>
</head>
<body ng-app="app">
<div>
    <div ng-view></div>
</div>
</body>
</html>

app.js:

'use strict';
angular.module('app', ['ngRoute', 'controllers'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: "templates/home.html",
                renderOnFirstLoad: false
            });

    }]);

controllers.js:

'use strict';
var controllers = angular.module('controllers',[]);

controllers.controller('HomeCtrl', ['$scope', function ($scope) {
    $scope.friends = {'name': 'name1', 'picture': {'data': {'url': 'url1'}}};
}
])

和templates / home.html

<div class="container-fluid" ng-controller="HomeCtrl" ng-cloak>
    <ul class="friends">
        <li ng-repeat="friend in friends" class="thumbnail">
            <div>
            <img src="{{friend.picture.data.url}}"/>
            </div>
            <p>{{friend.name}}</p>
        </li>
    </ul>
</div>

当我打开应用程序时,有两个 li 项目,但我在friends变量中只使用一个值。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

使用$scope.friends作为数组:

  'use strict';
    var controllers = angular.module('controllers',[]);

    controllers.controller('HomeCtrl', ['$scope', function ($scope) {
        $scope.friends = [{'name': 'name1', 'picture': {'data': {'url': 'url1'}}}];
    }
    ])

html代码:

<div class="container-fluid" ng-controller="HomeCtrl" ng-cloak>
    <ul class="friends">
        <li ng-repeat="friend in friends" class="thumbnail">
            <div>
            <img src="{{friend.picture.data.url}}"/>
            </div>
            <p>{{friend.name}}</p>
        </li>
    </ul>
</div>