在angularJs中,我有两个控制器,它们有一个共同的功能。我编写一个服务并将这个常用方法投入使用。
以下哪一种方法是正确的,或者有更好的方法可以做到这一点。
$scope
个对象来调用公共服务angular.module('app').controller('ACtrl', function($scope, $rootScope, MyCommonService) { $scope.firstObj = {....}; //can required more than 4 param MyCommonService.doCommontask(firstObj........); });
angular.module('app').service('MyCommonService', function(RestService)
{
this.doCommontask = function (firstObje.......) {
//following call is to service which do rest call and
//almost all work is inside the call back.
RestService.xxxGET().$promise.then(function(data)
{
// firstObje gets and others modified here and need
//value to be reflected in view controlled by ACtrl
// most of params of docommonTask used here
});
};
});
$rootScope
从controller
访问被修改的obj angular.module('app').controller('ACtrl', function($scope, $rootScope, MyCommonService) { //though $rootScope, will only used by this controller and,commonService $rootScope.firstObj = {....}; //no param as rootScope is used MyCommonService.doCommontask(); });
angular.module('app').service('MyCommonService', function($rootScope, RestService) {
this.doCommontask = function () {
//following call is to service which do rest call and
//almost all work is inside the call back.
RestService.xxxGET($rootScope.firstObj...).$promise.then(function(data){
// firstObje gets and others modified here and need
value to be reflected in view controlled by ACtrl
// most of params of docommonTask used here
});
};
});
要遵循哪一个或者有更好的方法/重构代码哪个有充分的理由?
请建议重构的最佳做法。