$ rootScope。$ watch触发了两次

时间:2015-05-20 17:31:41

标签: javascript angularjs watch

我希望在变量sprintf(tBuffer, "@%s%02X", cBuffer, modem_getChecksum(cBuffer)); fputs(tBuffer, MODEM); fputc(13, MODEM); 被更改后触发新的聊天:

    func addAnnotation(gesture: UIGestureRecognizer) {

    if gesture.state == UIGestureRecognizerState.Began {

        var touch = gesture.locationInView(self.Mapa)
        var coordinate = Mapa.convertPoint(touch, toCoordinateFromView: self.Mapa)

        var location = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)

        var loc = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)

        CLGeocoder().reverseGeocodeLocation(loc, completionHandler: { (placemarks, error) -> Void in

            if error == nil {
                let placemark = CLPlacemark(placemark: placemarks[0] as! CLPlacemark)

                self.cislo = placemark.subThoroughfare != nil ? placemark.subThoroughfare : ""
                self.adresa = placemark.thoroughfare != nil ? placemark.thoroughfare : ""
                self.mesto = placemark.subAdministrativeArea != nil ? placemark.subAdministrativeArea : ""
                self.krajina = placemark.administrativeArea != nil ? placemark.administrativeArea : ""
                let annotation = MKPointAnnotation()
                annotation.coordinate = placemark.location.coordinate
                annotation.title = self.adresa! + " " + self.cislo!
                self.Mapa.addAnnotation(annotation)
                println("Špendlík pridaný!")


            }

        })

    }

}

在我的newChat$rootScope.newChat = { roomId: roomId, friendId: friendId }; 变量中,如下所示:

ChatController

这在第一次重新加载页面后在我的页面上运行没有任何问题。但是对于第一次加载,此$watch会被触发两次,这会导致聊天的其他部分出现问题。

我检查了$rootScope.$watch('newChat', function (data) { /*do stuff*/ } 的值。这两次的价值完全相同。我的应用程序的其他任何部分都不使用$watch变量

为什么会这样,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

$ digest周期运行时,每个手表都会被触发。您需要做的是检查新值与旧值。

$rootScope.$watch('newChat', function (newValue, oldValue) {
    if(newValue !== oldValue){
        /*do stuff*/
    }
});

答案 1 :(得分:0)

我像这样解决了这个问题

$rootScope.$watch('someValue', function (){
                /* rewrite into a new scope */
                $scope.someValue = $rootScope.someValue;
            });
 $scope.$watch('someValue', function (){/*To do*/});