1

我已经为选项卡创建了一个 Angular JS 脚本,并尝试在 View 中访问下面的范围变量。但是,没有成功。选项卡单击工作正常,但稍后无法打印 selectedIndex 变量。请帮忙。

这是我认为的代码:

<nav id="App1" ng-app="navTab" ng-controller="NavTabController">
  <a href="#" ng-repeat="item in items" ng-class="{'selected-class-name':$index == selectedIndex}" ng-click="itemClicked($index)">{{item.product_name}}</a>
</nav>
{{selectedIndex}}

这是 Angular 脚本:

<script>
  var navTabModule = angular.module("navTab", [])
  navTabModule.controller("NavTabController", function($scope) {
    $scope.items = [
      {product_name: "dashboard"},
      {product_name: "contacts"},
      {product_name: "appointments"},
      {product_name: "todos"},
      {product_name: "transactions"},
      {product_name: "items"},
      {product_name: "calendar"},
      {product_name: "users"},
      {product_name: "reports"}
    ];
    $scope.selectedIndex = 0;
    $scope.itemClicked = function($index){
      $scope.selectedIndex = $index;
    }
  });
</script>
4

1 回答 1

2

您试图在元素之后访问范围之外的变量。nav

将绑定放在范围内,或将控制器移动到外部元素(使范围更广),它将起作用:

<nav id="App1" ng-app="navTab" ng-controller="NavTabController">
    <a href="#" ng-repeat="item in items" ng-class="{'selected-class-name':$index == selectedIndex}" ng-click="itemClicked($index)">{{item.product_name}}</a>
    {{selectedIndex}}
</nav>

或者

<div ng-app="navTab" ng-controller="NavTabController">
    <nav id="App1">
        <a href="#" ng-repeat="item in items" ng-class="{'selected-class-name':$index == selectedIndex}" ng-click="itemClicked($index)">{{item.product_name}}</a>
    </nav>
    {{selectedIndex}}
</div>
于 2013-11-02T11:42:10.910 回答