Angularjs 当我使用服务时,服务范围不知道控制器上的表单
我有以下代码工厂:Angularjs 当我使用服务时,服务范围不知道控制器上的表单,angularjs,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) { $sco
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
}
在我的页面上,我有一个表格:
<form class="form" name="modalForm">
<button data-ng-click="modalReset()">
Reset
</button>
重置
据我所知,此表单将动态添加到范围中,并显示为$scope.modalForm
当我的表单调用$scope.modalReset
时,它会执行,但当我使用调试器检查$scope时,$scope上没有modalForm
有人能解释为什么会这样吗。看起来,这项服务正在通过测试
范围在添加modalForm之前的早期阶段。是这样的吗?有没有
解决这个问题的方法?首先在工厂/服务中使用
$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) ;
}
}
}]);
angular.module('common'))
.工厂,
[“$http”、“$q”、“$resource”、“$rootScope”、“$timeout”、“\u o”、“\u u”,
函数($http、$q、$resource、$rootScope、$timeout、\u o、\u){
var_init=函数($scope){
$scope.modalReset=函数(){
_modalReset($scope);//您提到我应该在指令或控制器中编写逻辑,但在我的情况下,我这样做是因为有许多控制器共享相同的逻辑。还有其他更好的方法吗?谢谢您的建议。@SamanthaJ当然。如果在使用$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) ;
}
}
}]);