簡體   English   中英

如何在 angularjs 服務中使用 $scope

[英]how to use $scope in angularjs service

我將 api 響應存儲在$scope變量中。 我寫在我的主要 controller 中。 相反,我計划寫入一個服務文件,並需要在所有 controller 中使用它。 現在我正在重寫所有 controller 中的代碼。 所以我的應用程序變慢了。

主控制器.js:

$scope.UserId = reply.split('UserId=').pop().toUpperCase();
apiService.getResponseData($scope.UserId).then(function(reply) {
  $scope.responseData = reply.data;
  $timeout(function() {
    reply.data.forEach(function(card) {
      if (card.Category == 'Apple') {
        console.log("Apple");
      } else if (card.Category == 'Google') {
        console.log("Google");
      } else if (card.Category == 'Microsoft') {
        console.log("Microsoft");
      } else if (card.Category == 'Amazon') {
        console.log("Amazon");
      }
    });
  });
});

這是我的主控制器。 如何在我的 service.js 文件中使用相同的代碼。

CommonService.js:

app.service('commonService', ['$timeout', '$rootScope', 'apiService',
  function($timeout, $rootScope, apiService) {
    this.app = function($scope) {
      $scope.UserId = reply.split('UserId=').pop().toUpperCase();
      apiService.getResponseData($scope.UserId).then(function(reply) {
        $scope.responseData = reply.data;
        $timeout(function() {
          reply.data.forEach(function(card) {
            if (card.Category == 'Apple') {
              console.log("Apple");
            } else if (card.Category == 'Google') {
              console.log("Google");
            } else if (card.Category == 'Microsoft') {
              console.log("Microsoft");
            } else if (card.Category == 'Amazon') {
              console.log("Amazon");
            }

          });
        });
      });
      return app;
    };
  }
]);

$scope在服務文件中不起作用。 取而代之的是,我該如何以其他方式使用。 任何人都可以修改上面的代碼。 我想將此代碼從服務用於多個控制器..

可以使用但不是一個好案例

主控制器.js:

commonService.something($scope);

CommonService.js:

app.service('commonService', ['$timeout', '$rootScope', 'apiService',
    function ($timeout, $rootScope, apiService) {
        var something = function (scope) {
            apiService.getResponseData(scope.UserId).then(function (reply) {
                scope.responseData = reply.data;
                $timeout(function () {
                    reply.data.forEach(function (card) {
                        if (card.Category == 'Apple') {
                            console.log("Apple");
                        } else if (card.Category == 'Google') {
                            console.log("Google");
                        } else if (card.Category == 'Microsoft') {
                            console.log("Microsoft");
                        } else if (card.Category == 'Amazon') {
                            console.log("Amazon");
                        }

                    });
                });
            });
        };

        return {
            'something': something
        }
    }
]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM