我为标签创建了一个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>
答案 0 :(得分: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>