3

我想使用循环来创建我的导航 这是我的代码我一直收到一个错误,说它不会评估为字符串?我写的代码是这样它会循环遍历 $scope.navigation 并使用它来写出导航,这样我就不必写出每个列表和锚标记?

  <!DOCTYPE html>
  <html ng-app="Sample">
    <head>
       <title>Sample Angular App</title>
       <script src="Scripts/basket.js"></script>
       <link rel="stylesheet" href="css/global.css"/>
       <script src="Scripts/angular.min.js"></script>
       <script src="controllers/main.js"></script>
       <script src="routes/route.js"></script>
  </head>
   <body>
     <div class="navigation" ng-controller="AppCtrl">
         <ul class="cf" >
            <li class="link {{link.name}}" ng-class="{{link.name + 'Active'}}" ng-repeat="link in navigation">
              <a href="{{link.route}}" ng-click="setActive($index)">{{link.name |      uppercase}}</a> 
            </li>
        </ul>
     </div>
     <div class="wrapper">
       <div ng-view>

       </div>
     </div>
   </body>
  </html>

我的主要 js 脚本文件如下所示:

          function AppCtrl($scope) {

            $scope.navigation = [

                { name:"main", route:"#/"},
                { name:"edit", route:"#/edit" },
                { name: "save", route: "#/save" },
                { name: "settings", route: "#/settings" }

            ];

            $scope.currentPage = null;

            $scope.setCurrentPage = function (index) {

                $scope.currentPage = $scope.navigation[index];

            }

            $scope.setActive = function (index) {

                angular.forEach($scope.navigation, function (value, key) {

                   $scope[value.name + 'Active'] = "";

                });

             var active = $scope.navigation[index].name;

                $scope[active + 'Active'] = "active";


            }

        }

它一直给我一个错误,说 {{link.name}} 不能被评估为一个字符串,但它是一个字符串?有没有办法遍历 $scope.navigation 并让它输出导航,而不必手动写出来并仍然添加 setActive 函数?我对使用 angularjs 有点陌生。有没有办法解决这个问题,还是角度不允许以这种方式做事?

4

2 回答 2

7

There's a much better/easier way to accomplish setting a active CSS class. Just save a single value in your scope that holds the value of what is active. Something like this:

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

Then ng-class allows you to give it an map where "the names of the properties whose values are truthy will be added as css classes to the element" (From http://docs.angularjs.org/api/ng.directive:ngClass).

So you can set the CSS class if the $index is the activeIndex:

ng-class="{active: $index == activeIndex}"
于 2013-09-11T15:27:25.357 回答
2

我已经测试了 dnc253 的解决方案。但它似乎不再起作用了。

我必须创建一个这样的方法:

$scope.isActive = function(index){
    return $scope.activeIndex === index;
};

在 html 中:

ng-class="{active: isActive($index)}" 

这工作正常。

于 2015-07-20T10:10:33.163 回答