简体   繁体   English

将html元素ID传递给ng-class

[英]Passing html element id to ng-class

I am a beginner with Angular and ui-router. 我是Angular和ui-router的初学者。 I am trying to apply an active class for a tab in the header based on the current state name. 我正在尝试根据当前状态名称为标题中的选项卡应用活动类。

    <ul class="tabs">
        <li id="tab1" ng-class="navTabClass(this.id)">
            <a href="link1.html">Home
            </a>
        </li>
        <li id="tab2" ng-class="navTabClass(this.id)">
            <a href="link2.html">Sales
            </a>
        </li>
    </ul>

I have a function defined in the controller for determining the class by checking the tab id and current state name (after trimming out the the name for my parent views) 我在控制器中定义了一个函数,用于通过检查选项卡ID和当前状态名称来确定类(在为我的父视图修剪掉名称之后)

 `$scope.navTabClass = function(tabId) {
                            console.log(tabId);
                            var stateName = $state.current.name;
                            mainTab = stateName.split('.');
                            return (mainTab[1] === tabId) ? 'active' : 'passive';
                        }

I printed out the tabId received and it is always 'undefined'. 我打印出收到的tabId,它始终是“ undefined”。 Needless to say, the function always returns passive as the class name 不用说,函数总是返回被动作为类名

How do I pass the id value correctly to the controlled function ? 如何将id值正确传递给受控函数?

ng-class expects an object, so ng-class需要一个对象,所以

Try this instead: 尝试以下方法:

<ul class="tabs">
    <li id="tab1" ng-class="{'active': activeTab === 'tab1'}" ng-click="changeTab('tab1')">
        <a href="link1.html">Home
        </a>
    </li>
    <li id="tab2" ng-class="{'active': activeTab === 'tab2'}" ng-click="changeTab('tab2')">
        <a href="link2.html">Sales
        </a>
    </li>
</ul>

Then your JS would look like this: 然后您的JS将如下所示:

$scope.changeTab = function(tabName){
    $scope.activeTab = tabName;
    console.log('tabName', tabName);
}

This would flip the state of your tabs 这将翻转标签的状态

Hi please see that demo : 嗨,请看那个演示:

http://plnkr.co/edit/cyZPh5h1lIYykqrh8Igh?p=preview http://plnkr.co/edit/cyZPh5h1lIYykqrh8Igh?p=preview

you can use ui-sref-active directive more info you can find here 您可以使用ui-sref-active指令在此处找到更多信息

http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref-active http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref-active

 <ul class="tabs">
    <li id="tab1" ui-sref-active="active">
      <a ui-sref="state1">State 1</a>
    </li>
    <li id="tab2" ui-sref-active="active">
      <a ui-sref="state2">State 2</a>
    </li>
  </ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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