ng-repeat无效的自定义标签页

时间:2015-05-15 20:11:44

标签: javascript angularjs ionic-framework

当没有添加ng-repeat时,这种工作非常完美

<ul>          
    <li ng-class="{active:tab===1}"> 
      <a href ng-click="tab = tab==1 ? a : 1">Tab1</a>               
    </li>           
    <li ng-class="{active:tab===2}"> 
       <a href ng-click="tab = tab==2 ? a : 2">Tab2</a>              
    </li>           
    <li ng-class="{active:tab===3}"> 
      <a href ng-click="tab = tab==3 ? a : 3">Tab3</a>           
    </li>     
       </ul>      
    <br><br> 
    <p ng-show="tab === 1"> Tab1 content </p>           
    <p ng-show="tab === 2"> Tab2 content</p> 
    <p ng-show="tab === 3"> Tab3 content</p>        

仅在内容中添加np-repeat,而不是tab,这也很完美

   <ul>          
    <li ng-class="{active:tab===1}"> 
      <a href ng-click="tab = tab==1 ? a : 1">Tab1</a>               
    </li>           
    <li ng-class="{active:tab===2}"> 
       <a href ng-click="tab = tab==2 ? a : 2">Tab2</a>              
    </li>           
    <li ng-class="{active:tab===3}"> 
      <a href ng-click="tab = tab==3 ? a : 3">Tab3</a>           
    </li>     
       </ul>      
    <br><br> 
    <p ng-show="tab === {{$index}}" ng-repeat="data in data">
       <a ng-repeat="value in data.value">{{value.name}}</a>
    </p>                   

这里是代码我将ng-repeat添加到标签和内容,而不是

<ul>          
    <li ng-repeat="data in data" ng-class="{active:tab==={{$index}}}"> 
      <a href ng-click="tab = tab=={{$index}} ? a : {{$index}} ">Tab1</a>               
    </li>                      
     </ul>
    <br><br> 
    <p ng-show="tab === {{$index}}" ng-repeat="data in data">
       <a ng-repeat="value in data.value">{{value.name}}</a>
    </p>                   

那是没有意义的,我按照逻辑来编写代码,不知道为什么它不起作用,任何人都可以帮助PLZ

1 个答案:

答案 0 :(得分:1)

不要在表达式中使用插值{{}},ng-class / ng-show采用角度表达式,所以请尝试:

   <li ng-repeat="data in data" ng-class="{active:tab===$index}"> 
      <a href ng-click="tab = (tab== $index ? a : $index)">Tab1</a>               
    </li>                      
     </ul>
    <br><br> 
    <p ng-show="tab === $index" ng-repeat="data in data">
       <a ng-repeat="value in data.value">{{value.name}}</a>
    </p>   

另请注意,$index基于零,即从0开始,而不是1.另外需要注意的是,ng-repeat会创建子范围be aware of the nuances of child scope inheritance

所以

在您的控制器中:

//initialize:-
$scope.tab = {selected :0}

$scope.setTab = function(index){
     $scope.tab.selected = index;
}

$scope.isSelected = function(index){
   return $scope.tab.selected === index;
}

    <li ng-repeat="data in data" ng-class="{active: isSelected($index)}"> 
      <a href ng-click="setTab($index)">Tab1</a>               
    </li>                      
     </ul>
    <br><br> 
    <p ng-show="isSelected($index)" ng-repeat="data in data">
       <a ng-repeat="value in data.value">{{value.name}}</a>
    </p>