AngularJS $ timeout有时候工作有时不会

Mar*_*ara 2 browser-refresh angularjs angularjs-ng-repeat angularjs-timeout

我遇到了AngularJS和$ timeout的一些问题.
在页面加载后我需要运行一些代码.Http.get()加载项目,ng-repeat在表格中显示它们.然后我需要运行代码以在我单击它时突出显示行.

我找到了使用$ timeout的解决方案.

$timeout(function () {
    console.log('in timeout');
    $scope.highlightRows();
});
Run Code Online (Sandbox Code Playgroud)

这确实有效,但不是每次都有效.在函数中我记录表中的行数,有时我得到0,因此点击处理程序没有注册,突出显示不起作用.

$scope.highlightRows = function () {
    console.log($("#tripsTable").children("tbody").children("tr").length);
    $("#tripsTable").children("tbody").children("tr").children().click(function () {
        console.log('row click');
        $("#tripsTable").children("tbody").children("tr").removeClass("focusedRow");
        $(this.parentNode).addClass("focusedRow");
    });
};
Run Code Online (Sandbox Code Playgroud)

尝试模拟时我必须按Ctrl + F5刷新.

控制台日志:

in timeout tripsController.js:14
0 
Run Code Online (Sandbox Code Playgroud)

我找不到这个问题的任何溶液,有什么建议可以理解的:)
谢谢你
马克

编辑: 这是我的HTML

<table class="table table-bordered" id="tripsTable">@*table-hover*@
    <thead>
        ....
    </thead>
    <tbody>
        <tr ng-repeat="trip in tripsVM.tripsList | orderBy: 'startDate'" ng-class="(trip.tripID == 0) ? 'newRow' : ''" class="row">
            ....
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 8

这看起来像是一个时间问题.由于您没有为$ timeout函数提供持续时间参数,因此它会立即执行.这可能在ng-repeat完成呈现数据之前执行,因此似乎没有任何事情发生.作为测试,您可以尝试在$ timeout函数中添加一个大延迟,以查看是否会产生影响.如果确实如此,那么一旦您知道项目已经显示,您将需要考虑触发此方法.

$timeout(function () {
    console.log('in timeout');
    $scope.highlightRows();
}, 2000);
Run Code Online (Sandbox Code Playgroud)

另外我强烈建议你不要在你的控制器中做任何JQuery - 实际上我强烈建议你不要使用JQuery!

您可以使用角度指令(例如ng-click和ng-class)来完成所有这些逻辑.

<table><tbody><tr ng-repeat="item in items" ng-click="selectItem(item)" ng-class={'focusedRow': item === selectedItem}"><td>{{item.Name}}</td></tr></tbody></table>
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中有selectItem方法

$scope.selectItem = function (item) {
    $scope.selectedItem = item;
}
Run Code Online (Sandbox Code Playgroud)