0

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?

5
  • have you tried to use $watch() on the property(s) that you want to check? Commented Nov 27, 2015 at 6:12
  • What exactly is the problem, what have you tried? Stackoverflow is not a code generator ;-) Commented Nov 27, 2015 at 6:12
  • can you provide a plunker or jsfiddle. It will be much easy to give answer. Commented Nov 27, 2015 at 6:13
  • 1
    I think you can use $watch for your requirement. And also if you tell me the exact problem I think it will be good for us to give a good solution. So update your question with clear requirement. Commented Nov 27, 2015 at 6:14
  • Here's an example of how to use watch copied straight from the Angular API documentation: scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); where 'name' is a property of your scope. Commented Nov 27, 2015 at 6:16

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.