2016-03-04 52 views
0

我有一个ngRepeat功能打印一些div默认和DIV点击其中第一个具有活跃类我想设置在div点击活跃和其他的人用不活动类,我有下一个代码,但我不知道为什么不工作。AngularJS:ngClass不更新上ngClick

在我的控制器

$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到不活动并保持活动类。

希望你能帮助我。

回答

1

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

为了解决该问题,在控制器范围确定的对象:

$scope.sectionModel = {} 

而在视图中,使用

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

或者使用的函数的控制器范围改变的值activeSection

顺便提一下,我不会保存活动部分的索引,而是保存活动部分本身。这可以确保您的NG-重复会工作得很好,即使它使用一个过滤器,改变了部分订单的数量:

$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> 
+0

谢谢,它的工作! – SoldierCorp

+0

顺便说一句,你能告诉我如何存储活动部分,而不是使用索引? – SoldierCorp

+0

我编辑了我的答案。 –

1

其原因是,ngRepeat会创建自己的$scope - 这样你就不会实际更新activeSection你以为你是 - 你创建的ngRepeat范围(子)称为activeSection另一个变量。解决此问题的方法是使用$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> 

肯定阅读了有关$scope这个帖子和继承:What are the nuances of scope prototypal/prototypical inheritance in AngularJS?

+1

或者使用controllerAs并绑定到,例如,vm.activeSection –

+0

我见现在,感谢您的解释,但不幸的是不工作。 – SoldierCorp