2013-09-23 125 views
2

在我正在开发的一个webapp中,我试图在ng-switch(在ng-repeat内)中嵌套一个ng-switch,并发现内部开关评估没有发生。AngularJS中的嵌套ng-switch

在下面的切口向下例(和on Plunker),我希望看到:

  • d
  • ģ
  • ħ

但我实际看到的是:

  • 一个
  • (无)
  • (无)
  • ^h

在有萤火虫,第三和第四场检查有没有孩子超越 <div ng-switch on="el.n1.hasOwnProperty('n2')"> DIV 。

我对使用hasOwnProperty表示歉意,但我正在处理一些带可选字段的JSON。如果有更好的方法来切换场的存在,我会全力以赴。

<!doctype html> 
<html lang="en" ng-app> 
<head> 
     <meta charset="UTF-8"/> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> 
     <script> 
      function TestController($scope) 
      { 
       $scope.testExample = [ 
        { n : "A" }, 
        { n : "B" }, 
        { 
         n : "C", 
         n1 : { x : "D" } 
        }, 
        { 
         n : "E", 
         n1 : 
         { 
          x : "F", 
          n2 : { y : "G" } 
         } 
        }, 
        { n : "H" } 
       ]; 
      } 
     </script> 
</head> 

<body ng-controller="TestController"> 

    <ul ng-repeat="el in testExample"> 
     <li ng-switch on="el.hasOwnProperty('n1')"> 
      <div ng-switch-when="true"> 

       <div ng-switch on="el.n1.hasOwnProperty('n2')"> 
        <div ng-switch-when="true"> 
         {{el.n1.n2.y}} 
        </div> 

        <div ng-switch-default> 
         {{el.n1.x}} 
        </div> 
       </div> 

      </div> 

      <div ng-switch-default> 
       {{el.n}} 
      </div> 
     </li> 
    </ul> 
</body> 
</html> 

任何帮助感激地收到。

回答

2

你可以尝试使用Object.keys(el).indexOf('n1') > 0代替hasOwnProperty

<ul ng-repeat="el in testExample"> 
    <li ng-switch on="Object.keys(el).indexOf('n1') > 0"> 
     <div ng-switch-when="true"> 
      <div ng-switch on="Object.keys(el.n1).indexOf('n2') > 0"> 
       <div ng-switch-when="true">{{el.n1.n2.y}}</div> 
       <div ng-switch-default>{{el.n1.x}}</div> 
      </div> 
     </div> 
     <div ng-switch-default>{{el.n}}</div> 
    </li> 
</ul> 

在控制器中,不要忘了此行

$scope.Object = Object;