2015-12-29 62 views
1

我有看法:AngularJs活動導航項目的問題

<ul class="nav nav-pills" ng-controller="MenuItemCtrl as vm"> 
     <li ng-repeat="item in names" class="col-lg-2 col-md-2 col-sm-12 col-xs-12" ng-click="select($index)" ng-class="{active: $index == selected}"> 
      <a ng-show="{{item.up===true}}" href="#{{item.link}}">{{item.name}}</a> 
     </li> 
    </ul> 

和控制器這樣的:

$scope.names = [{ 
       name: "Main", 
       slug: "main", 
       active: true, 
       up:true, 
       inFooter:false, 
       link: "/" 
      }, { 
       name: "Pets", 
       slug: "pets", 
       active: false, 
       up:true, 
       link: "/pets" 
      }, { 
       name: "LDAdoption", 
       slug: "ldAdoption", 
       active: false, 
       inFooter:false, 
       up:true, 
       link: "/ldAdoption" 
      },{ 
       name: "Impressum", 
       slug: "impressum", 
       active: false, 
       up:false, 
       inFooter:true, 
       link: "/impressum" 
      }, { 
       name: "Be a volunteer", 
       slug: "volunteer", 
       active: false, 
       inFooter:true, 
       up:false, 
       link: "/volunteer" 
      }, { 
       name: "Contact", 
       slug: "contact", 
       active: false, 
       up:true, 
       inFooter:true, 
       link: "/contact" 
      }]; 
      $scope.selected = 0; 
     $scope.select= function(item) { 
      $scope.selected = item; 
    }; 

     $scope.isActive = function(item) { 
       return $scope.selected === item; 
      }; 

我不明白爲什麼活動狀態不保持,如果我刷新我的網頁。我與ng-route一起工作,一切都很好,只是活動狀態工作錯了。你能幫我嗎?謝謝!

+0

由於負荷後,你有'$ scope.selected = 0'和'$ scope.isActive()'將被解析成'0 === item'。 –

+0

,我該怎麼辦? –

+0

這取決於你想做什麼。 –

回答

0

在您的控制器啓動時,您應該以某種方式獲取當前路線,並根據此路線選擇特定項目。

例如,您可以slug字段添加到您的路線:

$routeProvider. 
    when('/pets', { 
     templateUrl: '...', 
     controller: /*...*/, 
     slug: 'pets' 
    }) /* ... */; 

,然後讀取它在你的控制器:

function yourController($scope, $routeParams) { 
    /*...*/ 
    var selectedSlug = $routeParams.slug; 
    if (selectedSlug) { 
     $scope.selected = /* find item by selected slug */ 
    } 
} 
0

添加 '塞' 到routeParams

$routeProvider. 
when('/pageUrl/:slug', { 
    templateUrl: viewUrl, 
    controller: someController 
}); 

In Controller

.controller('someController', function ($scope, $routeParams, $location) { 
    if ($routeParams.slug) { 
     $scope.selected = $routeParams.slug 
    } 

    $scope.select= function(slug) { 
     $location.path('/pageUrl/' + slug); 
    }; 

}) 

鑑於:

<ul class="nav nav-pills" ng-controller="MenuItemCtrl as vm"> 
    <li ng-repeat="item in names" class="col-lg-2 col-md-2 col-sm-12 col-xs-12" ng-click="select(item.slug)" ng-show="{{item.up===true}}" ng-class="{active: item.slug == selected}"> 
     <a href="javascript:void(0)">{{item.name}}</a> 
    </li> 
</ul> 
+0

不起作用這個想法。 –