search

Home  >  Q&A  >  body text

angular.js - angular passes $scope into service

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

我想大声告诉你我想大声告诉你2774 days ago704

reply all(4)I'll reply

  • ringa_lee

    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.

    reply
    0
  • 黄舟

    黄舟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.

    reply
    0
  • 某草草

    某草草2017-05-15 16:52:23

    Go to my blog and pass in callback parameters

    reply
    0
  • 高洛峰

    高洛峰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.

    reply
    0
  • Cancelreply