app.contronller('xxx', ['$scope', 'service', function($scope, service) {
$scope.xxx = 'xxxx';
service.say($scope);
}]);
app.service('xxx', [function() {
this.say = function($scope) {
}
}]);
现在维护的代码里好多这样的情形,这是不是错误的用法?感觉用起来很爽,但是代码好混乱
ringa_lee2017-05-15 16:52:23
This is obviously a lazy approach, causing the meaning of the service method to be very vague. When you pass $scope into it, it is completely unclear which parameters are actually used.
And it causes the service method to have unnecessary dependence on $scope.
黄舟2017-05-15 16:52:23
Strictly speaking, non-global status values should not be processed in the service, especially modifications. This is $scope. In other words, the service here is similar to an interface. The parameter list of the function should be clear, rather than general parameters.
Such as
app.contronller('xxx', ['$scope', 'service', function($scope, service) {
$scope.xxx = 'xxxx';
service.say($scope.xxx);
}]);
app.service('xxx', [function() {
this.say = function(word) {
}}]);
Of course, global variables such as $location and $rootScope can be used because they do not need to be passed through other components. They can be obtained through injection.
高洛峰2017-05-15 16:52:23
In fact, when I tested, I found that if you return the value in the service to $scope in the controller, the closure seems to have no effect. However, passing $scope in will directly update the $scope in the controller in the service. This works very well.