2016-03-04 50 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