gpt4 book ai didi

angularjs - 为什么AngularJS过滤器在ng-if中不起作用?

转载 作者:行者123 更新时间:2023-12-04 08:48:33 24 4
gpt4 key购买 nike

我有一个简单的 AngularJS 页面,其中包含在单击链接时显示和隐藏的不同部分。其中一个区域有一个可以过滤的重复列表。

当包含列表的部分以 ng-show 显示/隐藏时或 ng-hide它表现正常。当ng-if已使用,无法过滤列表。

演示

  • This version does not work due to the use of ng-if
  • This version does work due to the use of ng-show


  • 示例 HTML
    <nav>
    <a href="javascript:{}" ng-click="area='one';">Area 1</a>
    <a href="javascript:{}" ng-click="area='two';">Area 2</a>
    </nav>

    <div ng-if="area==='one'">
    <h3>Area 1!</h3>
    <input type="text" placeholder="filter list..." ng-model="filterText" />
    <ul>
    <li ng-repeat="item in list | filter: listFilter">
    {{item.id}} - {{item.name}}
    </li>
    </ul>
    </div>

    <div ng-if="area==='two'">
    <h3>Area 2!</h3>
    <p>Stuff here...</p>
    </div>

    示例 Angular
    $scope.area="one";
    $scope.filterText="";

    $scope.list = [
    {id:1, name:"banana"},
    {id:2, name:"apple"},
    {id:3, name:"orange"},
    {id:4, name:"pear"},
    {id:5, name:"apricot"}
    ];

    $scope.listFilter = function(item){
    var term = $scope.filterText.trim().toLowerCase();
    return item.id.toString().indexOf(term) > -1 || item.name.indexOf(term) > -1;
    };

    最佳答案

    我自己没有原型(prototype)继承这一主题的硕士学位,但我会尽快解释一下(关于这个主题有大量的资源);

  • Number
  • String
  • Boolean
  • null
  • undefined
  • Symbol (从 ES6 开始)

  • 被认为是 primitives (MDN) .

    现在 - 当您从父范围“继承”原语时,实际发生的是子范围“镜像”或“遮蔽”给定的原语值。因此,您可以将其视为上述内容的副本。

    这大致是原型(prototype)继承上下文中原语的本质。

    这可以在 modified version of your broken fiddle 中清楚地观察到。 .

    尝试使用两个输入,当您仅触摸外部输入时,您会看到两个值之间存在联系(即子值“遮蔽”父值)。但是,一旦您触摸内部输入,这些值就会彼此断开。

    推荐解决这个问题的方法是使用对模型(我说的是模型,但实际上它只是一个 JS 对象)上的属性的引用,该属性在原型(prototype)链的上游定义;
    $parentScope.obj = { filterText: '' };

    ng-model="obj.filterText"

    现在你应该很好地使用 ngIf , ngSwitch , ngRepeat列举一些创建新范围的 Angular 提供的指令。

    有关该主题的资源
  • understanding scopes @ angular
  • presentation by misko on the subject
  • stackoverflow answer by Mark Rajcok
  • the dot @egghead.io
  • google search 'dot ng model'
  • 关于angularjs - 为什么AngularJS过滤器在ng-if中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28096727/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com