ng-repeat不显示项目

时间:2016-06-29 23:02:00

标签: javascript angularjs angularjs-ng-repeat angularjs-ng-route

我的角度应用程序中有一个奇怪的错误,我的ng-repeat中的数据没有显示但是如果我刷新页面并导航到我的主页它会快速闪烁进入视图然后消失,我不知道为什么会发生这种情况有人可以帮帮我吗?

提前致谢

appRoutes.js

angular.module('appRoutes', []).config(['$routeProvider','$locationProvider', function($routeProvider, $locationProvider) {

$routeProvider

    // home page
    .when('/', {
        templateUrl: 'views/home.html',
        controller: 'MainController'
    })

    // characters page that will use the CharactersController
    .when('/characters', {
        templateUrl: 'views/characters.html',
        controller: 'CharactersController'
    });

$locationProvider.html5Mode(true);

}]);

CharactersCtrl.js

angular.module('CharactersCtrl', []).controller('CharactersController', function($scope) {

$scope.init = function(){
    $scope.getCharacters();
}

$scope.getCharacters = function(){

    $.ajax({
        url:'https://gateway.marvel.com/v1/public/characters?apikey=APIKEY',
        success:function(response){
            $scope.characters = response.data.results;
            console.log($scope.characters);
        },
        fail:function(){

        }
    });

}

$scope.init();

});

characters.js

<div>
<div class="text-center">
    <h1>Characters</h1>
</div>

<section id="character-section" class="row">

    <figure class="columns small-3" ng-repeat="hero in characters">
            <!-- <img ng-src="{{hero.thumbnail.path}}" alt="{{hero.name}}-image"> -->
        <figcaption>
            {{hero.name}}
        </figcaption>
    </figure>
</section>
</div>

的index.html

<body ng-app="marvelApp">

    <!-- HEADER -->
    <header>
        <nav class="navbar navbar-inverse">
            <div class="navbar-header">
                <a class="navbar-brand" href="/">Stencil: Node and Angular</a>
            </div>

            <!-- LINK TO OUR PAGES. ANGULAR HANDLES THE ROUTING HERE -->
            <ul class="nav navbar-nav">
                <li><a href="/characters">characters</a></li>
            </ul>
        </nav>
    </header>

    <!-- ANGULAR DYNAMIC CONTENT -->
    <main ng-view ></main>

</body>

app.js

angular.module('marvelApp', ['ngRoute', 'appRoutes', 'MainCtrl', 'CharactersCtrl', 'CharactersService']);

1 个答案:

答案 0 :(得分:0)

您正在使用jQuery ajax。在Angular范围之外修改时,Angular不会自动更新变量(在这种情况下,使用jquery ajax修改$scope.characters);

我建议你使用angular提供的$http服务进行ajax调用。

但是如果你坚持使用jquery ajax,你可以用

包装这段代码$scope.characters = response.data.results;
`$scope.$apply(function(){

})`

结果:

$scope.$apply(function(){
    $scope.characters = response.data.results;
})