AngularJS服务中的自定义功能

时间:2016-05-04 23:08:33

标签: javascript angularjs angularjs-service

所以我试图根据两个变量计算物品/产品的折扣价:零售价销售价格。 我在AngularJS服务中创建了一个名为calculateDiscount的函数,我希望在我的视图中返回计算出的值。我的问题是我的观点没有针对每个项目的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": "$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",
        "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": "$422.14",
        "saleprice": "$95.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"
            }
        ]
    }
]

的DataService

    (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));

3 个答案:

答案 0 :(得分:1)

我认为,你在某些控制器的方法中得到的东西是这样的:

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}}%。 我没有检查这段代码的工作,可能有一些语法错误,但它反映了概念

答案 1 :(得分:0)

尝试将OnActionExpandListener函数添加到OnCloseListener对象,就像其他函数一样,以便返回。

calculateDiscount

答案 2 :(得分:0)

Natalia Kamaeva帮助我在聊天室里弄清楚了。

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

一旦纳塔利娅帮助我在聊天室中弄明白,我想到了多个实现。我想分享其中两个:

<强> 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>

如果计算出的折扣是固定功能,在不久的将来不会改变,则此解决方案有效。但是从生产/商业的角度来看,将变量存储在某个地方并且能够操纵变量更有意义。

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

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

是否在calculateDiscount内烘焙DataService功能。以下是完整的实施。我还清理了一些代码,只关注重要方面。

HTML MARKUP

<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); enter image description here

注意如何在项目本身中返回折扣变量

这正是我想要实现的目标。