サービス内のモデルを監視しても変更をキャッチすることはありません

StackOverflow https://stackoverflow.com//questions/20032824

  •  21-12-2019
  •  | 
  •  

質問

私はこの単純な(はずの)問題に数時間格闘してきました。

私が得たものは次のとおりです。モデルの変更を監視し、それに応じてデータベースを更新するプロバイダーがあります。以下は、問題のある部分に焦点を当てたフィドルから抜粋したコードです。

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
                            }
                        } );
                }
            };

をチェックしてください フィドル 作業コード用。

ご協力をよろしくお願いいたします。

役に立ちましたか?

解決

がここにあります 作業用フィドル.

主な問題は次のとおりです。

  1. TestCtrl どのモジュールにも登録されていませんでした。そこで、電話して接続しました TestModule.controller.
  2. 綿密な監視が必要でした model. 。したがって、時計には 3 番目のパラメータが追加されました (次のように設定されます)。 true)。これにより、 model 物体。

完全なコードは次のとおりです。

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 );
                }
            };
        };
    });
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top