[英]Conditionally bind data in AngularJS
我有很多任務。 它們具有標題和標簽。
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-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>
您的數據將在您“處理”任務時自動更新。
要更新inboxTasks,可以使用$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]);
}
}
});
其他答案幫助我指出了正確的方向,但這是我如何使其工作的方法:
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
函數。 這就是所謂的“ 相等監視” ,它顯然需要更多的計算量,但這正是我所需要的。
這樣的問題和解答對類似的問題提供了有用的評論,也有很多技巧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.