1

I have created an Angular JS script for tabs and trying to access a scope variable below in View. But, no success. Tab click is working fine, but unable to print selectedIndex variable later. Please help.

This is the Code in my View:

<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}}

And here is the Angular Script:

<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>

1 Answer 1

2

You are trying to access the variable outside of the scope, after the nav element.

Put the binding inside the scope, or move the controller to an outer element (make the scope broader), and it will work:

<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>

or

<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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.