Pregunta

He estado luchando con este (supuestamente) problema simple durante varias horas.

Lo que tengo es:Hay un proveedor que observará los cambios del modelo y luego actualizará la base de datos en consecuencia.A continuación se muestra el código tomado del violín centrado en la parte que presenta el problema.

this.$get = function ( ) {
            return {
                listen: function ( $scope, model ) {
                    if ( !that.enabled ) return;
                    $scope.$watch( function () {
                            return $scope.model;
                        },
                        function ( newValue, oldValue ) {
                            if ( newValue != oldValue ) {
                                // never gets to this line !
                                alert('Cool !');

                                // .. rest of the code to proceed with db updates
                            }
                        } );
                }
            };

revisar la violín para el código de trabajo.

Cualquier ayuda es profundamente apreciada.

¿Fue útil?

Solución

Aquí hay un violín de trabajo.

Los principales problemas fueron los siguientes:

  1. TestCtrl no estaba registrado en ningún módulo.Así que lo conecté llamando TestModule.controller.
  2. Necesitabas una vigilancia profunda model.Entonces, ahora el reloj tiene un tercer parámetro (establecido en true).Esto observará las propiedades del model objeto.

Aquí está el código completo:

var TestModule = angular.module( 'TestModule', [ 'AutoSaveP' ] )
.config( function ( autoSaveProvider ) {
    autoSaveProvider.enabled = true;
    autoSaveProvider.tablename = 'test';
    autoSaveProvider.primary_field = 'test_id';
} );

TestModule.controller('TestCtrl', function( $scope, $timeout, autoSave ) {
    $scope.model = {
        test_id: 1,
        first_name: 'john',
        last_name: 'doe'
    };
    $timeout( function () {
        autoSave.listen( $scope, $scope.model );
    }, 100 );
});

var AutoSaveP = angular.module( 'AutoSaveP', [ ] )
.provider('autoSave',
     function () {
        this.enabled = true;
        this.table_name = null;
        this.primary_field = null;

        this.$get = function ( ) {
            return {
                listen: function ( $scope, model ) {
                    $scope.$watch( function () {
                            return $scope.model;
                        },
                        function ( newValue, oldValue ) {
                            if ( newValue != oldValue ) {
                                // now gets to this line!
                                alert('Cool !');

                                // .. rest of the code the proceed with db updates
                            }
                        }, true );
                }
            };
        };
    });
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top