【问题标题】:Conditionally bind data in AngularJS在 AngularJS 中有条件地绑定数据
【发布时间】:2014-09-15 20:42:00
【问题描述】:

我有一系列任务。他们有标题和标签。

function Task(taskTitle, taskType) {
  this.title = taskTitle;
  this.type = taskType;
}

$scope.tasks = [];

我最终声明了一堆不同类型的任务并将它们添加到数组中

在我的 html 中,我显示了一列卡片,按任务类型过滤:

<div ng-model="tasks">
  <div class="card" ng-repeat="abc in tasks track by $index" ng-show="abc.type==0">
    <p> {{ abc.title }} </p>
  </div>
</div>

我想将此过滤视图中显示的第一张卡片绑定到其他一些div。我将处理一个收件箱,所以我会将这张卡片列表缩减到零。每次我“处理”一张卡片并将其从列表中删除时,我都需要刷新数据。

<div ng-model="firstCardInFilteredArray">
  <h4>Title of first card:</h4>
  <p> This should be the title of the first card! </p>
</div>

我的直觉是做这样的事情(在 javascript 中):

// pseudo-code!
$scope.inboxTasks = [];
for (i=0; i<tasks.length(); i++) {
  if (tasks[i].type == 0) {
    inboxTasks.append(tasks[i]);
  }
}

并在页面更改时以某种方式再次运行该功能。但这似乎很荒谬,不符合 Angular 的精神。

在纯 javascript 或 Angular 中是否有一种简单的方法可以完成此条件绑定?

【问题讨论】:

  • ng-show="abc.type === 0 && $index > 0" 那么,splice-ing 数组中的第一个值将导致绑定更新。跨度>

标签: javascript angularjs data-binding


【解决方案1】:

您可以过滤您的 ng-repeat:https://docs.angularjs.org/api/ng/filter/filter

<div ng-model="tasks">
  <div class="card" ng-repeat="abc in filteredData = (tasks | filter: {type==0}) track by $index">
    <p> {{ abc.title }} </p>
  </div>
</div>

此外,通过将过滤后的数据保存在单独的列表中,您可以像这样显示下一个任务:

<div>
  <h4>Title of first card:</h4>
  <p> filteredData[0].title </p>
</div>

您的数据将在您“处理”任务时自动更新。

【讨论】:

  • 更新后不再需要自定义过滤器
  • 内联过滤可以工作,但我将如何“保存”filteredData?这不应该绑定到我的$scope 中声明的某个对象吗?
  • 无需声明。 Angular 将初始化filteredData 变量,你的$scope 可以访问它。
【解决方案2】:

其他答案帮助我指出了正确的方向,但这是我如何让它发挥作用的:

HTML

<input ng-model="inboxEditTitle" />

JS

$scope.filteredArray = [];
$scope.$watch('tasks',function(){
       $scope.filteredArray = filterFilter($scope.tasks, {type:0});
       $scope.inboxEditTitle = $scope.filteredArray[0].title;
    },true); // the 'true' keyword is the kicker

$watch 的第三个参数设置为true 意味着对我的tasks 数组中的任何数据的任何更改都会触发watch 函数。这就是所谓的平等表,它显然是计算密集型的,但正是我需要的。

This SO question and answer 对类似问题有有用的评论,还有很棒的小提琴。

More on different $watch functionality in Angular

【讨论】:

    【解决方案3】:

    要更新收件箱任务,您可以使用$watchCollection

    $scope.inboxTasks = [];
    
    $scope.$watchCollection('tasks', function(newTasks, oldTasks)
    {
       for (i=0; i<newTasks.length(); i++) 
       {
          if(newTasks[i].type == 0) 
          {
             $scope.inboxTasks.append(tasks[i]);
          }
       }
    });
    

    【讨论】:

    • 斯科特,我可能会考虑这个选项。这段代码中的newTasksoldTasks 指的是什么?
    • 只是进一步研究了它 - 这是一个语法问题。我实际上能够仅使用 $watch 解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 2019-08-19
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多