ng-repeat存储单独的值

时间:2014-10-01 12:45:42

标签: angularjs cookies ng-repeat voting

我想将用户投票存储在cookie中,问题是在ng-repeat内部我有一个名为session.upVoteCount的值。但它应该是每个事件列表项的单独值。是否可以单独存储每个upVoteCount,然后再单独检索它们?

<li ng-repeat="session in event.sessions | filter:query | orderBy:sortorder" class="span11">
                <div class="row session">
                    <div class="col-sm-1 well votingWidget">
                        <div class="votingButton" ng-click="upVoteSession(session)">
                            <span class="glyphicon glyphicon-arrow-up"></span>
                        </div>
                        <div class="badge badge-inverse">
                            <div>{{session.upVoteCount}}</div>
                        </div>
                        <div class="votingButton" ng-click="downVoteSession(session)">
                            <span class="glyphicon glyphicon-arrow-down"></span>
                        </div>
                    </div>

                </div>
            </li>

在我的控制器中我有这个:

$scope.upVoteSession = function(session) {
        session.upVoteCount++;            
    };

$scope.downVoteSession = function(session) {
        session.upVoteCount--;   
    };

2 个答案:

答案 0 :(得分:0)

首先,我不建议使用术语'会话',而是'投票'。但是,这是你的电话。

我在此示例中简化了您的问题

http://plnkr.co/edit/l7tQRbuOtEDJetY5eTsf?p=preview

使用Javascript:

function MyCtrl($scope) {
  $scope.votes = {};
  $scope.vote = function(key, val) {
    $scope.votes[key] = $scope.votes[key] || 0;
    $scope.votes[key]+= val;            
  };
}

HTML:

<li ng-repeat="no in [1,2,3,4,5]">
  {{no}} : {{votes[no]}} <br/>
  <a href="" ng-click="vote(no, +1)">upvote</a>
  <a href="" ng-click="vote(no, -1)">downvote</a>
</li>

答案 1 :(得分:0)

大家好我自己解决了,我无法让它与JSfiddle合作,所以我上传了整个内容。单击server.bat并浏览到localhost:8000 / eventdetails.html,您将看到它正常工作。

https://mega.co.nz/#!1d9yiYiA!zTzdztLAmhVDVYOvvVLINETI2bo_WjxCBteWYm2VUKc

控制器:

eventsApp.controller('EventController',
    function EventController($scope, $cookieStore, eventData) {
        $scope.sortorder = 'name';
        var ape = eventData.getEvent();
        ape.then(function (banana) {
            $scope.event = banana;
            angular.forEach(banana.sessions, function (value, key) {
                var storecookie = ($cookieStore.get(value.name));
                if (typeof storecookie !== "undefined") {
                    value.upVoteCount = storecookie;
                }
            });
        });
        $scope.upVoteSession = function (session) {
            session.upVoteCount++;
            $cookieStore.put(session.name, session.upVoteCount);
        };

        $scope.downVoteSession = function (session) {
            session.upVoteCount--;
            $cookieStore.put(session.name, session.upVoteCount);
        };
    }
);