Leif
Leif

Reputation: 335

How to implement two-way data binding with a for loop in angular.js?

I'm using angular.js and I want a for loop to run every time a property of a $scope object changes. How do I implement this?

Upvotes: 0

Views: 477

Answers (2)

Midhun Darvin
Midhun Darvin

Reputation: 1255

You can use $watch property to check the scope variable for changes. However $scope.$digest() function is called by angular internally when it first loads, this causes the listener function of $scope.$watch() to execute when the page first loads up. So in order for it to not run the first time i have included a first time check flag in the code.

index.html

<div ng-controller="MyCtrl">

    <select name="singleSelect" ng-model="data">
      <option value="option-1">Option 1</option>
      <option value="option-2">Option 2</option>
    </select><br>
    {{data}}
</div>

app.js

function MyCtrl($scope) {

    var firsttime = true;
    $scope.$watch('data',function() { 
        if(!firsttime){
            console.log("digest called"); 
            run();
            val = false;
        }
        firsttime = false;
    });

    var run = function(){
        for(var i=0;i<10;i++)
            console.log("Task"+ i);
    }    
}

Here is a working fiddle.

Upvotes: 1

Adam Zerner
Adam Zerner

Reputation: 19168

$scope.$watch is used to say, "when this property changes, run this callback" and can be used to do what you desire to do like so:

angular
  .module('app', [])
  .controller('MainController', MainController)
;

function MainController($scope) {
  $scope.property = 'initial';
  
  $scope.$watch('property', function() {
    for (var i = 0; i < 5; i++) {
      console.log(i);  
    }   
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>

<div ng-app='app'>
  <div ng-controller='MainController'>
    <input ng-model='property'>
    <p>{{ property }}</p>
  </div>
</div>

Upvotes: 1

Related Questions