获取ng-show值作为参考

时间:2013-11-07 14:11:48

标签: javascript html angularjs dom

我有以下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来连接变量名。

2 个答案:

答案 0 :(得分: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>

这是plunker demonstrating的变化。

答案 1 :(得分:0)

您可以在该对象中指定简单的更新程序功能:

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

然后叫它:

subNavMenuDisplays[name](true);