AngularJS:ngClass没有更新ngClick

时间:2016-03-04 19:19:14

标签: angularjs angularjs-ng-click ng-class

我有一个ngRepeat函数来打印一些div,默认情况下第一个有活动类,而div点击我想设置div点击活动和其他具有非活动类的人,我有下一个代码,但我不知道为什么不工作。

在我的控制器中

$scope.activeSection = 0;

在我看来

<div ng-repeat="div in divs" ng-class="activeSection == $index ? 'active' : 'inactive'" ng-click="activeSection = $index">
    <p>Lorem......</p>
</div>

这里的问题是当我点击时,点击的div变为活动状态,但不会将最后激活的div更改为非活动,而是保留活动类。

希望你能帮助我。

2 个答案:

答案 0 :(得分:1)

原因是,ngRepeat会创建自己的$scope - 因此您实际上并未更新您认为自己的activeSection - 您正在创建另一个名为{{1}的变量在activeSection范围(子)上。解决此问题的一种方法是使用ngRepeat(丑陋) - 或者只是调用控制器上的函数以确保达到正确的$parent

$scope

查看:

$scope.setActive = function(index) {
    $scope.activeSection = index;
}

绝对阅读有关<div ng-repeat="div in divs" ng-class="activeSection == $index ? 'active' : 'inactive'" ng-click="setActive($index)"> <p>Lorem......</p> </div> 和继承:What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

的帖子

答案 1 :(得分:1)

ng-repeat定义了自己的范围。所以当activeSection = $index时,设置ng-repeat的activeSection变量是什么。不是控制器的activeSection变量。

要解决此问题,请在控制器范围中定义一个对象:

$scope.sectionModel = {}

在视图中,使用

ng-class="sectionModel.activeSection == $index ? 'active' : 'inactive'" ng-click="sectionModel.activeSection = $index"

或者使用控制器范围中的函数来更改activeSection的值。

BTW,我会存储活动部分本身,而不是保存活动部分的索引。这确保你的ng-repeat工作正常,即使它使用的过滤器改变了部分顺序的数量:

$scope.activeSection = null; // or $scope.div[0] for example
$scope.setActiveSection = function(section) {
    $scope.activeSection = section;
}

<div ng-repeat="div in divs | orderBy:'title'" ng-class="activeSection === div ? 'active' : 'inactive'" ng-click="setActiveSection(div)">
    <p>Lorem......</p>
</div>