ng-show和ng-if无法显示内容

时间:2014-12-29 23:39:26

标签: javascript angularjs ng-show angular-ng-if

尝试构建一个简单的标签。选项卡0中的内容按预期显示和隐藏,但是,标签1仅为空白,尽管单击选项卡1时范围更新为真。

首先,控制器在包装器div上启动:

<div ng-controller="AdvancedSettingsController as settings">

这是控制器:

function AdvancedSettingsController($scope) {

    //setting tab name, and initial booleans
    $scope.tab = [
        {
            title : "Domains",
            active : true
        },
        { 
            title: "Locale",
            active : false 
        }
    ];

}

和ng-click监听器:

AdvancedSettingsController.prototype.tabs = function (o) {
    //set both tab active booleans to false
    for (var i = 0; i <= $scope.tab.length - 1; i++) {
        $scope.tab[i].active = false;
    }

    //set active tab boolean to true
    $scope.tab[o].active = true;

}

现在,使用ng-repeat-settings.tabs($ index)循环的制表符对象将索引传递给上面的函数:

<li data-ng-repeat="tab in settings.tab">
   <a data-ng-click="settings.tabs($index)">
      {{tab.title}}
   </a>
</li>

内容以2个div保存,ifs:

<div data-ng-if="settings.tab[0].active">
   Content 1, true by default. Hides and shows as nav is toggled.
</div>

<div data-ng-if="settings.tab[1].active">
   Content 2, false by default. Never shows as nav is toggled.
</div>

最后,Chrome从不更新if:       ngIf:settings.tab [1] .active

2 个答案:

答案 0 :(得分:1)

在您的html中,您尝试通过settings.tab和settings.tabs访问数据,但我看不到您在哪里定义设置......

按照您在此处发布的代码,我创建了此解决方案:http://codepen.io/anon/pen/raMbGr

<li ng-repeat="t in tab">
  <a ng-click="tabs($index)">
    {{t.title}}
  </a>
</li>

<div ng-if="tab[0].active">
  Content 1, true by default. Hides and shows as nav is toggled.
</div>

<div ng-if="tab[1].active">
  Content 2, false by default. Never shows as nav is toggled.
</div>

答案 1 :(得分:0)

我的问题的答案,在这里不明显,是我在第一个标签中有一个额外的结束div。它正在关闭ng-if然后出现了破损的标记。

我的代码看起来像这样:

<div ng-if="tab[0].active">
   <div>
      Content 1, true by default. Hides and shows as nav is toggled.
   </div>
   **</div>**
</div>

<div ng-if="tab[1].active">
  Content 2, false by default. Never shows as nav is toggled.
</div>

ng-if没有在正确的位置关闭 - 所以尽管$ scope更新,但html被破坏了。所以。烦。