0

我有以下html:

<div ng-show=showMarketingNav>
    ...
</div>

<div ng-show=showProductsNav>
    ...
</div>

<div ng-show=showSettingsNav>
    ...
</div>

我想要做的是能够轻松地从另一个控制器隐藏除一个 div 之外的所有 div。我以为我可以很聪明,做以下事情:

var subNavMenuDisplays = {
    Marketing: $scope.showMarketingNav,
    Products: $scope.showProductsNav,
    Settings: $scope.showSettingsNav
}

$rootScope.hideContextMenu = function () {
    for (var category in subNavMenuDisplays) {
        subNavMenuDisplays[category] = false;
    }
}

$rootScope.setContextMenu = function (name) {
    $rootScope.hideContextMenu();
    subNavMenuDisplays[name] = true;
}

但这显然不起作用,因为 $scope.showMarketingNav 等将作为值传递,而不是引用。

以下工作,但不是很好用:

$rootScope.hideContextMenu = function () {
    $scope.showMarketingNav = false;
    $scope.showProductsNav = false;
    $scope.showSettingsNav = false;
}

$rootScope.setContextMenu = function (name) {
    $rootScope.hideContextMenu();
    if (name == "Marketing") {
        $scope.showMarketingNav = true;
    }
    if (name == "Products") {
        $scope.showProductsNav = true;
    }
    if (name == "Settings") {
        $scope.showSettingsNav = true;
    }
}

有没有办法通过引用来获取 $scope.showMarketingNav 或另一种巧妙的方法?

我不想使用 eval 来连接变量名。

4

2 回答 2

1

您可以在 $scope 上放置一个对象,然后动态切换它:

$scope.show = {};

$rootScope.setContextMenu = function (name) {
    $scope.show = {};
    $scope.show[name] = true;
}

和HTML:

<div ng-show="show.Marketing">
    ...
</div>

<div ng-show="show.Products">
    ...
</div>

<div ng-show="show.Settings">
    ...
</div>

这是一个展示变化的笨蛋。

于 2013-11-07T14:17:42.790 回答
0

您可以在该对象中分配简单的更新函数:

Marketing: function(val) { $scope.showMarketingNav = val },
Products: function(val) { $scope.showProductsNav = val}, 
Settings: function(val) { $scope.showSettingsNav = val}

然后调用它:

subNavMenuDisplays[name](true);
于 2013-11-07T14:17:34.410 回答