Angular.js - ng-repeat不起作用

时间:2015-10-07 20:42:59

标签: angularjs ng-repeat

Angular.js对我来说很新鲜。我在控制器的$ scope方法之前已经学会了,现在尝试使用“this”方法。出于某种原因,我无法让我的ng-repeat工作。这是我的代码:

HTML:          
    

    <ul class="nav nav-pills">
        <li><a ng-click="myCtrl.tab=1" href>one</a></li>
        <li><a ng-click="myCtrl.tab=2" href>two</a></li>
        <li><a ng-click="myCtrl.tab=3" href>three</a></li>
    </ul>

    <div ng-controller="imageContr as imageCtrl">
        <div ng-show="myCtrl.tab === 1" class="tab">
            <h3>ONE title</h3>
            <p>hello</p>
            <li ng-repeat="item in gallery">
                <img alt="imagealt" ng-src="{{item.photo}}">
            </li>
        </div>
        <div ng-show="myCtrl.tab === 2" class="tab">
            <h3>TWO title</h3>
            <p>how are</p>

        </div>
        <div ng-show="myCtrl.tab === 3" class="tab">
            <h3>THREE title</h3>
            <p>you?</p>

        </div>
    </div>
</section>


</body>
</html>

APP.JS:

(function() {
var app = angular.module('myApp', []);
app.controller('myController', function() {
    this.tab = 1;
});
app.controller('imageContr', function() {
    this.gallery = images;
    var images = {
        photo: 'image1.jpg'
    };
});
})();

2 个答案:

答案 0 :(得分:0)

在分配图像之前声明图像,并使其成为数组

var images = [{ photo: 'image1.jpg' }];
this.gallery = images;

然后在你看来:

<li ng-repeat="item in imageCtrl.gallery">
    <img alt="imagealt" ng-src="{{item.photo}}">
</li>

答案 1 :(得分:0)

您将gallery存储在控制器的this上(基本上是$scope),因此您需要通过imageContr在模板中访问它:

<li ng-repeat="item in imageCtrl.gallery">
   <img alt="imagealt" ng-src="{{item.photo}}">
</li>

您还可以考虑将gallery作为数组,因此可以轻松地对其进行迭代。或者您需要使用"iterate over object properties" - 语法:

<div ng-repeat="(key, value) in myObj"> ... </div>