在服务中观看模型永远不会发现任何变化

时间:2013-11-17 15:59:34

标签: angularjs angularjs-service

我几个小时一直在努力解决这个(应该是)简单问题。

我得到的是:有一个提供商将观察模型更改,然后相应地更新数据库。以下是关于问题部分的小提琴代码。

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

查看fiddle的工作代码。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

这是working fiddle

主要问题是:

  1. TestCtrl未在任何模块中注册。所以,我通过拨打TestModule.controller来连接它。
  2. 您需要对model进行深入观察。所以,现在手表有第三个参数(设置为true)。这将关注model对象的属性。
  3. 以下是完整代码:

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