AngularJS 服务中的自定义函数

Custom Function in AngularJS Service

所以我试图根据两个变量计算应用于 items/products 的折扣价:零售价 销售价。 我在我的 AngularJS 服务中创建了一个名为 calculateDiscount 的函数,我想 return 我的视图中的计算值。我的问题是我的视图没有更新每个项目 calculated discount percentage

下面是我的代码

HTML 标记:

<div class="articleItem swiper-slide" ng-repeat=
    "item in items | orderBy:'-likes'">
        <div class="sales-discount">
            <i class="icon-tag"></i> Save {{calculateDiscount(item)}}%
        </div>
        <div class="article-title">
            <span class="badge badge-rect-white">Bestseller</span>
            <span class="badge badge-rect-black">On sale</span>
            <h2 style=
            "font-family: 'Lato', Arial, Tahoma, sans-serif; font-size: 26px; margin: 0; line-height: 1.2; text-shadow: 1px 1px 0 rgba(0, 0, 0, 0.8); font-weight:900;">
            <a href="javascript:;" style=
            "color:#fff;">{{item.productName}}</a>
            </h2>
            <div class="shop-data" style="margin-top:10px;">
                <!--<span class="shop-price" style="font-weight:900;
                                                            background-color: rgb(62, 123, 42);
                                                            padding: 5px;
                                                            border-radius: 3px;
                                                            color: #fff;">
                                   {{item.price}}
                                </span>-->
                 <span class="shop-price" style=
                "font-weight:900; background-color: rgb(62, 123, 42); padding: 5px; border-radius: 3px; color: #fff;">
                {{item.saleprice}}</span> <span class="data"><span style=
                "font-weight:900"><input id="box1" ng-model="item.likes"
                ng-value="item.likes" type="checkbox"> <label for="box1"
                style=
                "padding: 5px; background-color: #222; position: relative; top: 0; border-radius: 3px; margin-right:5px;">
                {{item.likes}}</label> <input id="box2" ng-model=
                "item.comments" ng-value="item.comment_count" type=
                "checkbox"> <label for="box2" style=
                "padding: 5px; background-color: #222; position: relative; top: 0; border-radius: 3px; margin-right:5px;">
                {{item.comment_count}}</label> <input id="box3" ng-model=
                "item.shares" ng-value="item.share_count" type="checkbox">
                <label for="box3" style=
                "padding: 5px; background-color: #222; position: relative; top: 0; border-radius: 3px; margin-right:5px;">
                {{item.share_count}}</label></span></span>
            </div>
        </div><img alt="" class="itemImgStyler" ng-src="{{item.picture}}"
        style="width:100%;">
    </div>

示例数据 data.json

    [

    {
        "_id": "5702bdbce518778bbc5add77",
        "index": 1,
        "guid": "694aafa9-b641-478a-a258-c2f0989f20dc",
        "isOnsale": true,
        "price": "9.53",
        "saleprice": ".73",
        "picture": "https://s-media-cache-ak0.pinimg.com/564x/d7/24/f2/d724f20fb401e010d601842584b5419f.jpg",
        "review": 4,
        "size": "L",
        "brand": "GUESS",
        "productType": "BEAUTY",
        "category": "SWEATERS",
        "productName": "Guess Men's Grey Sweater Two-Tones",
        "company": "LUXURIA",
        "phone": "+1 (842) 527-3928",
        "address": "674 Autumn Avenue, Haena, Massachusetts, 471",
        "likes": 34,
        "comment_count": 6,
        "share_count":20,
        "description": "Eu exercitation labore sint laborum nisi consequat pariatur sunt. Ullamco sit dolor velit ea excepteur cupidatat amet id Lorem anim enim consectetur ipsum eu. Laboris Lorem id exercitation occaecat irure aliquip veniam in ut. Esse velit occaecat cillum fugiat mollit ullamco do non cupidatat nulla ea esse aliquip cupidatat. Consectetur duis laborum fugiat laboris. Adipisicing fugiat dolor velit incididunt. Fugiat nisi dolor consequat amet et sint et aliquip qui consectetur.",
        "comments": "Non et elit ullamco est officia in. Velit ut nisi sunt mollit. Adipisicing est amet ipsum anim. Sunt aliquip irure aliqua non labore ut nulla.\n\nIrure fugiat ullamco enim elit sunt exercitation nisi. Ex consequat amet velit do ea veniam Lorem anim ipsum dolore ipsum aliqua culpa irure. Mollit irure aliquip ad elit ut consectetur proident amet et veniam nulla deserunt cupidatat culpa. Do duis sit elit voluptate fugiat anim ad id irure. Deserunt amet veniam nisi non.",
        "registered": "Sunday, November 2, 2014 12:41 PM",
        "latitude": "-6.226487",
        "longitude": "-111.623657",
        "tags": [
            7,
            "consequat qui"
        ],
        "range": [
            0,
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9
        ],
        "friends": [
            3,
            {
                "id": 1,
                "name": "Webb Rodriguez"
            }
        ]
    },
    {
        "_id": "5702bdbc1406dffa4188cc24",
        "index": 2,
        "guid": "27c7292b-a6a7-4145-afba-def743043941",
        "isOnsale": true,
        "price": "2.14",
        "saleprice": ".89",
        "picture": "https://s-media-cache-ak0.pinimg.com/564x/b0/4c/35/b04c353ddf167ad87b19fab56aa16ac3.jpg",
        "review": 3,
        "size": "XXL",
        "brand": "NIKE",
        "productType": "SNEAKERS",
        "category": "SHOES",
        "productName": "NIKE Men's Shoes Two-Tones",
        "company": "ZENTILITY",
        "phone": "+1 (827) 471-2811",
        "address": "650 Clifton Place, Keyport, Pennsylvania, 9913",
        "likes": 458,
        "comment_count": 149,
        "share_count":82,
        "description": "Cillum consectetur ut cupidatat officia ex elit aliqua. Quis nisi officia deserunt sit cillum commodo consectetur pariatur eu voluptate mollit qui magna. Culpa sunt qui nulla sit esse fugiat fugiat deserunt culpa.",
        "comments": "Mollit commodo dolore sit nulla. Ea excepteur cillum in ullamco. Laborum ea laboris voluptate anim laboris elit consectetur elit cillum.\n\nLabore esse laboris occaecat laboris. Velit exercitation in qui exercitation aliqua in qui. Consectetur reprehenderit culpa culpa exercitation commodo cupidatat consequat laborum reprehenderit non aliqua voluptate labore id. Deserunt dolor voluptate aliquip aliqua elit nulla id veniam laborum veniam aute magna minim. Ut non eiusmod qui cupidatat elit. Pariatur laboris duis ea qui in minim sit. Ut nostrud ex deserunt proident.",
        "registered": "Sunday, June 22, 2014 12:32 AM",
        "latitude": "-52.134773",
        "longitude": "77.284837",
        "tags": [
            7,
            "consequat qui"
        ],
        "range": [
            0,
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9
        ],
        "friends": [
            3,
            {
                "id": 1,
                "name": "Webb Rodriguez"
            }
        ]
    }
]

数据服务

    (function (ng) {
    'use strict';

    angular.module('data.services', [ ])
        .factory('dataService', ['$http', function($http) {
            console.log('dataService');

            var urlBase = "main-services/data.json";
            var calculateDiscount;
            var dataItems = {};

            dataItems.getAllItems = function () {
                return $http.get(urlBase,{
                    cache:true
                });

            };

            dataItems.addNewItem = function (item) {
                return $http.post(urlBase+'/addNewItem', item);
            };
            calculateDiscount = function(item){
                return ((item.saleprice/item.price)*100);
            }

            return dataItems;


        }]);


}(angular));

尝试将 calculateDiscount 函数添加到 dataItems 对象,就像其他函数一样,这样它就会被返回。

dataItems.calculateDiscount = function(item){
    return ((item.saleprice/item.price)*100);
}

我想,你在某些控制器的方法中得到的项目是这样的:

dataService.getAllItems()
    .then(function(response){$scope.items = response.data;})

如果是这样,您可以像这样更改 getAllItems 方法:

dataItems.getAllItems = function () {
   return $http.get(urlBase,{
                cache:true
            })
         .then(function(response){
               var items = response.data;
               items.forEach(function(item){
                   item.discount = calculateDiscount(item);
                })
               return items;
          });
    };

然后,在您的 html 中,将 <i class="icon-tag"></i> Save {{calculateDiscount(item)}}% 替换为 <i class="icon-tag"></i> Save {{item.discount}}%。 我没有检查这个代码是否工作,可能有一些语法错误,但它反映了概念

Natalia Kamaeva 在聊天室帮我解决了这个问题。

我犯的一个错误,也许是我花了一整天的时间,只是处理调试,是在我的 Data.json 文件中包含 $ 符号 salepriceprice 我项目对象的属性。所以当我尝试 return (item.saleprice/item.price)*100 时,我总是得到 NAN.

的值

Natalia 在聊天室中帮助我解决问题后,我想到了多种实现方式。我想分享其中两个:

1.简单的解决方案(并不总是推荐,但在某些情况下有效)

<div class="articleItem  swiper-slide" ng-repeat="item in items | orderBy:'-likes'">
     <div class="sales-discount">
          <i class="icon-tag"></i>Save {{(item.saleprice/item.price)*100}}%
     </div>
</div>

如果计算出的折扣是近期不会更改的固定函数,则此解决方案有效。但是从 production/business 的角度来看,将该变量存储在某个地方并能够对其进行操作更有意义。

这让我想到了第二个解决方案

2。我认为最好的解决方案(感谢 Natalia :))

就是在DataService里面烘焙calculateDiscount函数。下面是完整的实现。我还稍微清理了代码,只关注重要的方面。

HTML 标记

<div class="articleItem  swiper-slide" ng-repeat="item in items | orderBy:'-likes'">
     <div class="sales-discount">
          <i class="icon-tag"></i>Save {{item.discount}}%</div>
</div>

示例数据 data.json

[

{
    "_id": "5702bdbce518778bbc5add77",
    "index": 1,
    "guid": "694aafa9-b641-478a-a258-c2f0989f20dc",
    "isOnsale": true,
    "price": "439.53",
    "saleprice": "22.73",
    "picture": "https://s-media-cache-ak0.pinimg.com/564x/d7/24/f2/d724f20fb401e010d601842584b5419f.jpg",
    "review": 4,
    "size": "L",
    "brand": "GUESS",
    "productType": "BEAUTY",
    "category": "SWEATERS",
    "productName": "Guess Men's Grey Sweater Two-Tones",
    "company": "LUXURIA",
    "phone": "+1 (842) 527-3928",
    "address": "674 Autumn Avenue, Haena, Massachusetts, 471",
    "likes": 34,
    "comment_count": 6,
    "share_count":20,
    "description": "Eu exercitation labore sint laborum nisi consequat pariatur sunt. Ullamco sit dolor velit ea excepteur cupidatat amet id Lorem anim enim consectetur ipsum eu. Laboris Lorem id exercitation occaecat irure aliquip veniam in ut. Esse velit occaecat cillum fugiat mollit ullamco do non cupidatat nulla ea esse aliquip cupidatat. Consectetur duis laborum fugiat laboris. Adipisicing fugiat dolor velit incididunt. Fugiat nisi dolor consequat amet et sint et aliquip qui consectetur.",
    "comments": "Non et elit ullamco est officia in. Velit ut nisi sunt mollit. Adipisicing est amet ipsum anim. Sunt aliquip irure aliqua non labore ut nulla.\n\nIrure fugiat ullamco enim elit sunt exercitation nisi. Ex consequat amet velit do ea veniam Lorem anim ipsum dolore ipsum aliqua culpa irure. Mollit irure aliquip ad elit ut consectetur proident amet et veniam nulla deserunt cupidatat culpa. Do duis sit elit voluptate fugiat anim ad id irure. Deserunt amet veniam nisi non.",
    "registered": "Sunday, November 2, 2014 12:41 PM"

}
]

注意这里 discount 没有属性。这将被注入到我们的服务中,因为它是一个计算值。

数据服务

(function (ng) {
    'use strict';
angular.module('data.services', ['pinStyle'])
    .factory('dataService', ['$http', function ($http) {
        console.log('dataService');

        var urlBase = "main-services/data.json";
        var calculateDiscount;
        var dataItems = {};

        dataItems.getAllItems = function () {
            return $http.get(urlBase, {
                cache: true
            })
                .then(function (response) {
                    var items = response.data;
                    items.forEach(function (item) {
                        item.discount = calculateDiscount(item);
                    })
                
                return items;
                
                });
        };

        return dataItems;

    }]);

} (angular));

控制器调用

(function (ng) {
'use strict';

angular.module('feed.controllers', ['pinStyle', 'data.services'])
    .controller('feedController', ['$scope', 'dataService', function ($scope,dataService) {
        console.log('feedController');


        var items;
        var status;
        getItems();

        function getItems() {
            dataService.getAllItems()
                .then(function (itm) {
                    $scope.items = itm;
                    console.log($scope.items);
                });
        };
    }]);
}(angular));

我的结果 console.log($scope.items);

注意 discount 变量是如何在项目本身中返回的

这正是我 wanted.to 实现的。