angular.js - angular passes $scope into service
我想大声告诉你
我想大声告诉你 2017-05-15 16:50:23
0
4
709
app.contronller('xxx', ['$scope', 'service', function($scope, service) {
    $scope.xxx = 'xxxx';

    service.say($scope);
}]);

app.service('xxx', [function() {
    this.say = function($scope) {
    }
}]);

There are many such situations in the code being maintained. Is this a wrong usage? It feels great to use, but the code is so confusing

我想大声告诉你
我想大声告诉你

reply all(4)
左手右手慢动作

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.

黄舟

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.

某草草

Go to my blog and pass in callback parameters

小葫芦

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template