如何在 AngularJS 服务中使用 $scope



我将我的 api 响应存储在$scope变量中。我已经在我的主控制器中写了。取而代之的是,我计划写入一个服务文件,并需要在所有控制器中使用它。现在我正在所有控制器中重写代码。所以我的应用程序越来越慢。

主控制器.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");
}
});
});
});

这是我的主控制器。如何在我的服务.js文件中使用相同的代码。

公共服务.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);

公共服务.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
}
}
]);

最新更新