在循环中构建菜单链接时检查是否存在状态

时间:2016-08-26 10:27:07

标签: javascript angularjs angular-ui-router

我正在尝试使用以下数组创建导航链接:

JS:

$scope.sidebarLinks = [
    {
        name: 'Dashboard',
        state: 'dashboard',

    },
    {
        name: 'Students',
        state: 'student.list'
    },
    {
        name: 'Organization',
        children: [
            {
                name: 'School Profile',
                state: 'schoolProfile.detail',
            },
        ],
    },
]

HTML:

<ul>
  <li ui-sref-active="active" ng-repeat="x in sidebarLinks">
    <a ui-sref="{{x.state}}"></a>
  </li>
</ul>

由于“组织”的状态未定义,因此ui-sref为空。 所以有错误说:

  

错误:无效状态参考''

我在以下答案中找到了某种黑客攻击:

How to achieve that "ui-sref" be conditionally executed?

是否有某种(黑客)方法可以解决问题而无需为此创建新功能或控制器?

1 个答案:

答案 0 :(得分:0)

如果您不希望使用其他功能,则可以使用ng-if提供ui-sref的链接(如果已设置状态,并且如果状态未定义则为{。}}。

如果未使用{{x.state || myOtherState }}

定义状态,则可以默认为其他状态

由于您的组织中有孩子,我猜ng-if变体最适合您,如果您希望显示子项,则需要额外的HTML。