1

I am trying to put a watch on a variable, so that if it's value changes I call the rest service and get updated count.

Here is how my code looks like

function myController($scope, $http) {

    $scope.abc = abcValueFromOutsideOfMyController;    

    $scope.getAbcCnt= function()
    {
        url2 = baseURL + '/count/' + $scope.abc;

        $http.get(url2).success(function (data) {
            $scope.abcCnt = data.trim();
        });
    };

    $scope.$watch('abc',getAbcCnt);
}

But, I get following error

ReferenceError: getAbcCnt is not defined

I am new to AngularJS, let me know if there is some fundamental concept I am missing and above is not possible to do.

This answer didn't help me AngularJS : Basic $watch not working

Community
  • 1
  • 1
Watt
  • 3,118
  • 14
  • 54
  • 85
  • 1
    do you mean `$scope.$watch('abc',$scope.getAbcCnt);` – Ruan Mendes May 10 '13 at 16:21
  • You've just asked a second, different question. Each post should be about a single question, not a whole problem. Suggestion: ask a new question and link to this. That makes the questions more useful and searchable to others. – Ruan Mendes May 10 '13 at 16:40
  • Ok, I will move it in a separate one. – Watt May 10 '13 at 16:40
  • I moved it to a separate post http://stackoverflow.com/questions/16487102/using-angularjs-watch-to-get-drop-down-selected-item-not-working – Watt May 10 '13 at 16:46

2 Answers2

5

You need to reference it in the $scope.

$scope.$watch('abc', $scope.getAbcCnt);

If you were to declare your function without the $scope prefix your existing call would work, but you would not be able to access the function from the view. If you don't need to access the function from the view, you can declare the function without the $scope and keep your existing $watch statement.

Nicholas Pappas
  • 10,439
  • 12
  • 54
  • 87
  • +1 Thanks, I was missing that. This error went away, but I get undefined for $scope.abc, I am going to update the question on how I set $scope.abc value – Watt May 10 '13 at 16:32
  • stackoverflow.com/questions/16487102/… is follow up issue – Watt May 10 '13 at 16:49
1

I think you meant

$scope.$watch('abc',$scope.getAbcCnt); 
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • Thanks! There is typo in AngularJS book $scope.$watch(' funding.startingEstimate', computeNeeded); Green, Brad; Seshadri, Shyam (2013-04-08). AngularJS (Kindle Locations 665-668). O'Reilly Media. Kindle Edition. – Watt May 10 '13 at 16:27
  • @Watt I suspect that `computeNeeded` is not defined on the scope in that example. – Jim Cote Aug 11 '14 at 00:17