0

I'm new to AngularJS, I was trying a code with ng-repeat but got stuck because I need to pass the angular expression to a function but it is not working below is my code:

HTML code

     <div ng-controller="Profile as pro">
      <ul class="nav nav-tabs">
       <li ng-repeat="tabs in tabArray" 
           ng-class="{active: pro.tab==1}" 
           ng-click=" pro.setTab({{tabs.value}})">
         <a href="">{{tabs.name}}</a>
       </li>
      </ul>
     <div>

Controller code

controller.controller('Profile', ['$scope',function ($scope) {
        $scope.tabArray = [
            {name:"Profile","value":1},
            {name:"Education","value":2},
            {name:"Work","value":3},
            {name:"About","value":4}
        ];
        this.tab=1;
        this.setTab = function(tabSelected){
            this.tab=tabSelected;
        };
     }]);

3 Answers 3

1

Use ng-click ="pro.setTab(tabs.value)"

Sign up to request clarification or add additional context in comments.

Comments

0

Only proble in your code is in following line:

ng-click=" pro.setTab({{tabs.value}})" // don't use {{ and }} thing here, it is not needed

Following code is fixed version:

ng-click="pro.setTab(tabs.value)" // only {{ and }} are removed and it works well

Happy Helping!

Comments

0

There were some mistakes in your existing code ->

  1. Since you are making use of ControllerAs syntax, you should refer with the variable used for the controller, with all the variables referenced in the view.

Here, in the ng-repeat of your model refer by pro.tabArray.

  1. There is no need to pass the parameters in AngularExpressions, at the time of function/method call.

So, make use of ng-click="pro.setTab(tabs.value)", without the expressions.

HTML Code:

<li ng-repeat="tabs in pro.tabArray" ng-class="{'active': pro.tab==1}" ng-click="pro.setTab(tabs.value)"><a href="">{{tabs.name}}</a></li>
  1. In your JS too, you have referred some varibales with $scope and some with this. Be consistent with your code and do not mix it.

JS Code:

var app = angular.module('app', []);

app.controller('Profile', function ($scope) {
    this.tabArray = [
              { name: "Profile", "value": 1 },
              { name: "Education", "value": 2 },
              { name: "Work", "value": 3 },
              { name: "About", "value": 4 }
    ];
    this.tab = 1;
    this.setTab = function (tabSelected) {
        this.tab = tabSelected;
    };
    $scope = this;
});

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.