0

Startin out with angularjs this issue has puzzled me.

howcome and how can I make sure that when the watch function runs 2nd time (on init) testValue is "changed".

<div ng-controller="MyCtrl"></div>

and js :

var myApp = angular.module('myApp',[]); 
function MyCtrl ($scope) {
  var testValue = null;
  $scope.watchMe = null;        
  $scope.$watch('watchMe', function () {
    console.log('testValue is', testValue);        
    if(testValue !== null){`enter code here`
        console.log('i want to do something different the 2nd time this code runs - but i never get in here...');
    }
    testValue ="changed";
  });
};

And then there is the fiddle : jsfiddle example of the code

Thank you very much

doniyor
  • 36,596
  • 57
  • 175
  • 260
Jitter
  • 1
  • 2

2 Answers2

0

the way you are trying to use watch is not very much correct

watch is used to react on a model change to trigger some further actions

so you need set a model as watch expression and listen to it so that when there is any change watch is called

<div ng-app="myApp" ng-controller="MyCtrl">
  <input type="text" ng-model="name" placeholder="Enter your name">
  <p>{{greeting}}</p>
</div>

and js :

var myApp = angular.module('myApp',[]); 
function MyCtrl($scope) {
  $scope.name = "";

  $scope.$watch("name", function(newValue, oldValue) {
    if ($scope.name.length > 0) {
      $scope.greeting = "Greetings " + $scope.name;
         console.log("change detected: " + newValue);
    }
  });
}
Abhishek Kumar
  • 2,136
  • 3
  • 24
  • 36
  • Thank you very much for taking the time to answer - turns out though the problem was elsewhere - see answer – Jitter Aug 10 '14 at 19:30
0

it turns out the problem wasn't in the watch but in the controller being called twice. I am not sure why it does this in the fiddle but i added a log to make it clear that this is the problem.

So to clearify - testValue keeps being null because after the watch function runs the controller function runs again and overwrites var testValue.

This can be due to a lot of thing - in my case I assigned the controller to an element as also seen in the fiddle.

<div ng-controller="MyCtrl"></div>
Jitter
  • 1
  • 2