AngularJS中的控制器

Jac*_*001 -1 angularjs

我正在尝试使用AngularJS app种子并得到一些奇怪的结果.

在view2.html我有:

<div ng-controller="view_ctrl_2">
    <div id="view2">
        <table class="table table-striped">
            <thead>
                <tr>
                    <td>col1</td>   <td>col2</td>   <td>col3</td>   <td>col4</td>
                </tr>
            </thead>
            <tr ng-repeat="entry in entries">
                <td>{{entry.col1}}</td> <td>{{entry.col2}}</td> <td>{{entry.col3}}</td> <td>{{entry.col4}}</td>
            </tr>
        </table>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

在我的controllers.js文件中,我有

angular.module('myApp.controllers', [])
    .controller('view_ctrl_2', [function() {
        var entries = [
                { "col1":"val01", "col2":"val02", "col3":"val03", "col4":"val04" },
                { "col1":"val05", "col2":"val06", "col3":"val07", "col4":"val08" },
                { "col1":"val09", "col2":"val10", "col3":"val11", "col4":"val12" }
        ];
    }]);
Run Code Online (Sandbox Code Playgroud)

但是,我没有在页面上获得任何输出.它显示了表格,但ng-repeat没有在其上放置任何行.我的猜测是我错过了与$ scope变量有关的事情?

luc*_*uma 5

您需要添加entries到$ scope:

angular.module('myApp.controllers', [])
    .controller('view_ctrl_2', ['$scope', function($scope) {
        $scope.entries = [
                { "col1":"val01", "col2":"val02", "col3":"val03", "col4":"val04" },
                { "col1":"val05", "col2":"val06", "col3":"val07", "col4":"val08" },
                { "col1":"val09", "col2":"val10", "col3":"val11", "col4":"val12" }
        ];
    }]);
Run Code Online (Sandbox Code Playgroud)

请注意,$scope正在注入控制器['$scope', function($scope)...并使用$scope.entries=而不是var entries=

为了进一步阐述,需要注入控制器的所有依赖关系.如果您正在进行一些http调用并使用promises,它将如下所示:

 .controller('view_ctrl_2', ['$scope', '$q', '$http', function($scope, $q, $http)
Run Code Online (Sandbox Code Playgroud)