gpt4 book ai didi

javascript - 将代码移至 Angular 应用程序中的工厂中

转载 作者:行者123 更新时间:2023-12-03 10:49:58 26 4
gpt4 key购买 nike

我正在尝试清理一个包含太多代码行的 Controller 。在下面的 Controller 中,您可以找到一个名为 getProductDetails 的函数,我想将过滤器移动到工厂或服务,但我不知道该怎么做。

'use strict';

(function () {
var userQuoteBuild = angular.module('priceApp');
userQuoteBuild.controller('quoteBuilderController', function ($scope, $http) {

// loads of controller logic here...

$scope.getProductDetails = function (item) {

$scope.listOfProductVariants = item.default_variant_attributes;

// TODO: put this in its own factory?
$scope.selectedProductAttributes = $scope.listOfAttributes.filter(function (item) {
var validated = false, i, length = $scope.listOfProductVariants.length;
for (i = 0; i < length; i++) {
if (item.name === $scope.listOfProductVariants[i]){
validated = true;
}
}
return validated;
});
};



});

最佳答案

(function () {

'use strict';

angular
.module('priceApp')
.factory('filterService', filterService);

function filterService() {
var service = {
getValidated: getValidated
}

return service;

function getValidated(list, variants) {
return list.filter(function (item) {
var validated = false, i, length = variants.length;
for (i = 0; i < length; i++) {
if (item.name === variants[i]) {
validated = true;
}
}
return validated;
});
}
}
})();

只需将此 filterService 注入(inject)到您的 Controller 中,然后按照此处的示例使用它:

     $scope.selectedProductAttributes = filterService
.getValidated($scope.listOfAttributes,
$scope.listOfProductVariants)

我关注了John Papa's AngularJS Style Guide 。确保选择一个比 filterService 更好的名称。 :)

关于javascript - 将代码移至 Angular 应用程序中的工厂中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28456854/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com