Search code examples
javascriptangularjsdata-binding

Conditionally bind data in AngularJS


I have an array of tasks. They have titles and and labels.

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

$scope.tasks = [];

I end up declaring a bunch of tasks with different types and adding them to the array

In my html, I show a column of cards, filtered by type of task:

<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>

I want to bind the first card displayed in this filtered view to some other div. I'll be processing an inbox, so I'll whittle this list of cards down to zero. Each time I 'process' a card and remove it from the list, I need the data to refresh.

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

My intuition was to do something like this (in javascript):

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

and somehow run that function again any time the page changes. But that seems ridiculous, and not within the spirit of Angular.

Is there a simple way in pure javascript or with Angular that I can accomplish this conditional binding?


Solution

  • The other answers helped point me in the right direction, but here's how I got it to work:

    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
    

    Setting the third argument of $watch to true means that any changes to any data in my tasks array triggers the watch function. This is what's known as an equality watch, which is apparently more computationally intensive, but is what I need.

    This SO question and answer has helpful commentary on a similar problem, and a great fiddle as well.

    More on different $watch functionality in Angular