1

这是一个 ngRepeat,它为用户重复警报。我想在一段时间内一一显示每个警报。我正在使用 ngShow 和一个计数器变量$scope.showedItem

模板

        <div class="container" >
            <div ng-repeat="headerNotification in headerNotification.list" ng-show="{{showedItem==$index}}">
                    <h3>{{headerNotification.getText()}}</h3>
                    <button ng-click="headerNotification.do()" class="btn btn-warning">{{headerNotification.getButtonText()}}</button>
            </div>
        </div>

控制器

componentHeaderModule.controller('headerController', [
'$rootScope',
'$scope',
'componentHeaderNotification',
'$interval',
function ($rootScope, $scope, componentHeaderNotification, $interval)
{
    ...
    $scope.showedItem = 1;

    $interval(function(){
        $scope.showedItem++;
        if ($scope.showedItem > $scope.headerNotification.list.length)
            $scope.showedItem = 0;
    }, 5000);
}]);

当我查看DeveloperTool时,我看到ng-show值每 5 秒更改一次,但是,视图没有刷新,始终显示相同的警报。甚至,项目类没有改变。

可能是什么问题呢?我对双向绑定的理解是一个很大的错误?

4

1 回答 1

1

ngShow计算角度表达式,因此您不希望在其中使用双花括号。

所以里面:

<div ng-repeat="headerNotification in headerNotification.list" ng-show="{{showedItem==$index}}">

改变这个:

ng-show="{{showedItem==$index}}"

对此:

ng-show="showedItem==$index"

默认情况下,Angular 不会$watch添加属性(这对性能有很大帮助)。这就是为什么 Angular 期望你传入一个表达式来进行计算。

当您在表达式中使用双花括号时,会发生花括号内的表达式被评估一次,当指令被链接并且结果(在您的情况下为trueor false)然后被传递并永远使用,永远不会改变 -即使属性的值发生变化,Angular 也不会注意到(因为$watch它上面没有)。

例如,如果showedItem在链接完成时等于 0,则ngRepeat传递第一个条目,true同时传递所有其他条目false- 导致您所看到的,ngShow永远不会改变。

您希望每个 $digest 循环都对表达式求值,以便将表达式传入。

于 2014-01-20T17:49:30.190 回答