【问题标题】:AngularJS ngHide and ngShow depending on <select> optionAngularJS ngHide 和 ngShow 取决于 <select> 选项
【发布时间】:2015-05-14 15:24:56
【问题描述】:

我正在尝试使用 ngHide/ngShow 根据您在标签中选择的选项更改视图,但我似乎无法弄清楚如何使其工作。

这是我目前的想法:

<header class="hero-unit" id="banner" ng-include="'components/header/header.html'"></header>

<div ng-include="'components/navbar/navbar.html'"></div>


<div class="container">
    <h3 class="site-headline">Opret nyt produkt</h3> <hr>
    <form> 
        <div class="container jumbotron">
            <div class="col-md-12">
                <select>
                    <option ng-repeat="option in options" name="chosenOption">
                        {{ option.name }}
                    </option>
                </select>
            </div>

            <div ng-show="{{ option.name }} == 'Pool'" ng-include="'new-pool.html'"></div>

        </div>
    </form>
</div>

<footer class="footer" ng-include="'components/footer/footer.html'"></footer>

但我似乎无法访问 {{ option }},这是有道理的,因为我不在 ng-repeat 范围内。

我试过这个方法:

$scope.setProduct = function(productName){
    $scope.product = productName;
    console.log($scope.product);
};

只需调用 select 标签上的 ng-change,即可设置 product.name = selectedOption。它确实打印出正确的 $scope.product,但没有显示 ng-include。

我似乎无法绕过它,并且可以伸出援助之手。

【问题讨论】:

    标签: javascript angularjs scope


    【解决方案1】:

    您需要将ng-model 添加到&lt;select&gt;

    <div class="container jumbotron">
        <div class="col-md-12">
            <select ng-model="selectedOption">
                <option ng-repeat="option in options" name="chosenOption">
                    {{ option.name }}
                </option>
            </select>
        </div>
    
        <div ng-show="selectedOption.name == 'Pool'" ng-include="'new-pool.html'"></div>
    
    </div>
    

    选择时的ng-model 将被设置为当前选择的对象。

    【讨论】:

    • 我得到这个控制台错误:Error: [$parse:syntax] Syntax Error: Token '==' not a primary expression at column 1 of the expression [== 'Pool'] starting at [== 'Pool'].
    • 那是因为你不需要 {{ }}ng-show 中。我已经更新了我的答案。
    • 好的,我已经整理好了,但是 ng-show 仍然没有出现。
    • 没关系,我明白了。我只需要从 == 'Pool' 中删除 '
    • 好吧,还是不太行。出于某种原因,ng-show 没有隐藏ng-include。无论如何,它只显示 div
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多