当我使用服务时,我的控制器上的表单不为服务范围所知

时间:2014-03-01 08:09:08

标签: angularjs

我有以下代码工厂:

angular.module('common')
    .factory('_g',
    ['$http', '$q', '$resource', '$rootScope', '$timeout', '_o', '_u',
    function ($http, $q, $resource, $rootScope, $timeout, _o, _u) {

        var _init = function ($scope) {
            $scope.modalReset = function () {
                _modalReset($scope); // << No modalForm appears on this scope
            };
        };
        var _modalReset = function ($scope) {
            $scope.modalForm.$setPristine();
        };

        return {
           init: _init,
           modalReset: _modalReset
        }

在我的控制器中,我在代码的开头初始化这样的服务:

   _g.init($scope);

在我的页面上,我有一个表单:

   <form class="form" name="modalForm">
      <button data-ng-click="modalReset()">
          Reset
      </button>

根据我的了解,此表单将动态添加到范围并显示为$ scope.modalForm

当我的表单调用$scope.modalReset时,它执行但是当我用调试器检查时,$ scope上没有modalForm。

有人可以解释为什么会这样。看起来这个服务正在通过 在添加modalForm之前的早期阶段。是这样的,有一个 我可以解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:1)

首先$scope用于工厂/服务是不好的做法。服务是单身人士。

这个逻辑你可以在指令或控制器中写。

无论如何,从你的例子中我看不出你以某种方式$scope作为两个方法的参数传递。我会把工厂换成:

angular.module('common')
    .factory('_g',
    ['$http', '$q', '$resource', '$rootScope', '$timeout', '_o', '_u',
    function ($http, $q, $resource, $rootScope, $timeout, _o, _u) {

        var _init = function ($scope) {
            $scope.modalReset = function () {
                _modalReset($scope); // << No modalForm appears on this scope
            };
        };
        var _modalReset = function ($scope) {
            $scope.modalForm.$setPristine();
        };

       return {
        init: function ($scope) {                
           return _init($scope) ;
        },
        _modalReset: function ($scope) {                
           return _init($scope) ;
        }
     }
    }]);