简体   繁体   中英

how to set methods name dynamically in Angularjs

I have multiple tabs in a page,by clicking any of them I want to call a method: HTML:

@foreach (Tabs tab in Enum.GetValues(typeof(Tabs)))
  {
    <uib-tab index="@((int)tab)">
        <uib-tab-heading ng-click="tabSelected('@tab')">
        </uib-tab-heading>
    </uib-tab>
  }

AngularJS:

$scope.tabSelected = function (tab) {
        $scope[tab]();
      };

now I get Error said: $scope[tab]() is not a function! How can I fix it?

I think defining all functions before $scope.tabSelected is your answer.

Javascript works from top to bottom, so your functions must be delcared before this function.

$scope.x = function() {

};

$scope.y = function() {

};

$scope.z = function() {

};

$scope.tabSelected = function(tab) {
  $scope[tab]();
};

A working example:

 angular.module("app", []).controller("text", [ "$scope", function($scope) { $scope.x = function() { console.log("x"); }; $scope.y = function() { console.log("y"); }; $scope.z = function() { console.log("z"); }; $scope.tabSelected = function(tab) { $scope[tab](); }; } ]); 
 <div ng-app="app"> <div ng-controller="text"> <button ng-click="tabSelected('x')">X</button> <button ng-click="tabSelected('y')">Y</button> <button ng-click="tabSelected('z')">Z</button> </div> </div> 

CodePen

your code should be:

$scope.tabSelected = function (tab) {
        $scope.selectedTab = tab;
      };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM