简体   繁体   English

在AngularJS控制器

[英]Controllers in AngularJS

I'm trying to use the AngularJS app seed and am getting some odd results. 我正在尝试使用AngularJS应用程序种子,并得到一些奇怪的结果。

In view2.html I have: 在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>

and in my controllers.js file I have 在我的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" }
        ];
    }]);

However, I'm not getting any output on the page. 但是,我在页面上没有任何输出。 It shows the table, but the ng-repeat isn't putting any rows on it. 它显示了该表,但ng-repeat并未在其上放置任何行。 My guess is that I'm missing something to do with the $scope variable? 我的猜测是我缺少与$ scope变量有关的东西吗?

You need to add entries to the $scope: 您需要添加entries到$范围:

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" }
        ];
    }]);

Please note that $scope is being injected to the controller ['$scope', function($scope)... and the use of $scope.entries= instead of var entries= 请注意, $scope正在注入到控制器['$scope', function($scope)... ,并且使用$scope.entries=而不是var entries=

To further elaborate, all dependencies for the controller need to be injected. 为了进一步详细描述,被注射控制器需要所有的依赖。 If you were making some http calls and using promises it would look like this: 如果您正在进行一些http调用并使用promises,则它将如下所示:

 .controller('view_ctrl_2', ['$scope', '$q', '$http', function($scope, $q, $http)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM