【问题标题】:ng-show nested in ng-repeat won't update嵌套在 ng-repeat 中的 ng-show 不会更新
【发布时间】:2015-08-08 20:58:02
【问题描述】:

我查看了 SO 和 Google 的所有内容,发现了 ng-show 无法在 ng-repeat 内部工作的一大堆原因(范围问题、绑定问题等),但我无法完全确定为什么我的不工作。我希望多一双眼睛能帮助我。我对 Angular 很陌生,所以希望我的代码有些有意义。

目标:当$scope.current_set改变时,可见的lmf-optionset改变。目前,只有第一个选项集通过Decision_Tree:loaded 加载,然后当我尝试通过clickbox:clicked 加载下一个选项集时,$scope.current_set 更改,但视图不会更新。

JS

angular.module('lmf.option_set', [])
  .controller('OptionsetCtrl', ['$scope', 'Optionsets', 'Decision_Tree',
    function($scope, Optionsets, Decision_Tree) {
      $scope.Optionsets = Optionsets;
      $scope.current_set = {
        name: null
      };

      $scope.$on('clickbox:clicked', function() {
        $scope.current_set = Decision_Tree.get_next_optionset();
      });

      $scope.$on('Decision_Tree:loaded', function() {
        $scope.current_set = Decision_Tree.get_next_optionset();
      });
    }
  ])

HTML

<div ng-controller='OptionsetCtrl'>
  <div ng-repeat='set in Optionsets.option_sets'>
    <div ng-show="set.name == current_set.name" lmf-optionset="{{set.name}}"></div>
  </div>
</div>

【问题讨论】:

    标签: javascript angularjs ng-repeat ng-show


    【解决方案1】:

    显然lmf-optionset 为每个条目创建了一个隔离范围。这些子作用域与父作用域的current_set 有链接,但它们不维护双向绑定。因此,当您在事件处理程序中替换 current_set value 时,子范围不知道 current_set 已更改,并且它们仍在引用旧值。

    您可以像这样重写您的事件处理程序:

    $scope.current_set.name = Decision_Tree.get_next_optionset().name;
    

    或者你可以像这样使用controller as 构造:

    <div ng-controller='OptionsetCtrl as vm'>
      <div ng-repeat='set in Optionsets.option_sets'>
        <div ng-show="set.name == vm.current_set.name" lmf-optionset="{{set.name}}"></div>
      </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 2014-02-27
      相关资源
      最近更新 更多