seyid yagmur
seyid yagmur

Reputation: 1722

angularjs $watch not working in function

I have a problem with using $watch.When I use $watch out of the function below,it is working without any problems.But it doesn t affect When I use it inside the click function. I am waiting your suggestions..

 $scope.d = 1;
    var mark = L.marker(L.latLng(veri.Konum.lat, veri.Konum.lon), { title: veri.Name, data: veri, content: "" });
 mark.addTo(markersLayer);
 mark.on('click', onClick);

 function onClick(e) {

  $scope.$watch("d", function () {
        console.log("12313sadad");
    });
}

Upvotes: 2

Views: 2417

Answers (5)

sumit_suthar
sumit_suthar

Reputation: 462

try this.

$scope.$watch(function() {
        return variableToWatch;
    }, function(newVal, oldVal) {
        if (newVal !== oldVal) {
            //custom logic goes here......
        }
    }, true);

Upvotes: 1

Vicky Kumar
Vicky Kumar

Reputation: 1418

First thing is that

$scope.$watch is not part to be executed when required it must be compiled as directive load or as controller loads if you write it within function it will not be compiled initially so whenever you call a function try to execute $scope.$watch at that point you are trying to put watch on something("b") and your expectation is that from now on wards it will start watching that variable which but this not purpose of watch it is that you need to keep watch on "d" all the time not when required if you want to perform some operation as and when required then watch is not right approach you can simply write function

Upvotes: 0

ojus kulkarni
ojus kulkarni

Reputation: 1907

try this i m not prety sure about it but i guess it will work

scope.$watch("d", function (data) {
    console.log("data ",  data);
})

Upvotes: -1

Poyraz Yilmaz
Poyraz Yilmaz

Reputation: 5857

You put watch into a function which is not triggered by any angular component so angularjs is not aware what did you do inside of that function.

You should either trigger that function with some angular components (like ng-click, ng-change...) or you should call $scope.$apply() after set watch (it is not recommended though but you should do it if there is no other alternative)...

Upvotes: 4

Dan M. CISSOKHO
Dan M. CISSOKHO

Reputation: 1075

try this :

 function onClick(e) {
     if( !$scope.isWatched ) {
         $scope.$watch("d", function () {
             console.log("12313sadad");
             $scope.isWatched = true;
        });
     }
}

Upvotes: 0

Related Questions