【问题标题】:angularjs restricting count to current scopeangularjs将计数限制为当前范围
【发布时间】:2014-11-10 12:41:20
【问题描述】:

我正在尝试设置一个计数器,我可以为列表中的每个国家/地区计算点击次数以及总体计数。

到目前为止,我有以下内容,可以在this fiddle 中查看。我遇到的问题是我无法为每个国家/地区保持唯一的计数。如何实现?

    <div ng-app="myApp">
    <div data-ng-view></div>
    </div>

    'use strict';
    var myApp = angular.module('myApp', ['ngRoute', 'templates/view1.html', 'templates/view2.html']);

    myApp.config(['$routeProvider', function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'templates/view1.html',
                controller: 'CountryListCtrl'
            })
            .when('/:id', {
                templateUrl: 'templates/view2.html',
                controller: 'CountryCtrl'
            })
    }]);

    myApp.factory('Countries', ['$q', function ($q) {
        var countriesList = [];    
        // perform the ajax call (this is a mock)
        var getCountriesList = function () {
            // Mock return json
            var contriesListMock = [
                {
                    "id": "0",
                        "name": "portugal",
                        "abbrev": "pt"
                }, {
                    "id": "1",
                        "name": "spain",
                        "abbrev": "esp"
                }, {
                    "id": "2",
                        "name": "angola",
                        "abbrev": "an"
                }
            ];
            var deferred = $q.defer();
            if (countriesList.length == 0) {
                setTimeout(function () {
                    deferred.resolve(contriesListMock, 200, '');
                    countriesList = contriesListMock;
                }, 1000);
            } else {
                deferred.resolve(countriesList, 200, '');
            }
            return deferred.promise;
        }

        var getCountry = function(id) {
            var deferred = $q.defer();
            if (countriesList.length == 0) {
                getCountriesList().then(
                    function() {
                        deferred.resolve(countriesList[id], 200, '');
                    },
                    function() {
                        deferred.reject('failed to load countries', 400, '');
                    }
                );
            } else {
                deferred.resolve(countriesList[id], 200, '');
            }
            return deferred.promise;
        }

        var cnt      = 0;
        var cntryCnt = 0;    

        var incCount = function() {
               cnt++;
               return cnt;        
        }

        var incCntryCount = function(id) {
               cntryCnt++;
               return cntryCnt;        
        }

        return {
            getList: getCountriesList,
            getCountry: getCountry,
            getCount : function () {
                return cnt;
            },
            getCntryCount : function () {
                return cntryCnt;
            },        
            incCount: incCount,
            incCntryCount: incCntryCount      
        };
    }]);

    myApp.controller('CountryListCtrl', ['$scope', 'Countries', function ($scope, Countries) {
        $scope.title = '';
        $scope.countries = [];
        $scope.status = '';

        Countries.getList().then(
            function (data, status, headers) { //success
                $scope.countries = data;
            },
            function (data, status, headers) { //error
                $scope.status = 'Unable to load data:';
            }
        );
    }]);

    myApp.controller('CountryCtrl', ['$scope', '$routeParams', 'Countries', function ($scope, $routeParams, Countries) {
        $scope.country = {
            id: '',
            name: '',
            abbrev: ''
        };
        var id = $routeParams.id;

        Countries.getCountry(id).then(
            function(data, status, hd) {
                console.log(data);
                $scope.country = data;
                $scope.countOverall = Countries.getCount;
                $scope.countCntry = Countries.getCntryCount;
                $scope.clickCnt = function () {
                    $scope.countTotal = Countries.incCount();
                    $scope.country.clicks = Countries.incCntryCount(id);
                    console.log($scope);
                };  
            },
            function(data, status, hd) {
                console.log(data);
            }
        );   

    }]);


    angular.module('templates/view1.html', []).run(["$templateCache", function ($templateCache) {
        var tpl = '<h1>{{ title }}</h1><ul><li ng-repeat="country in countries"><a href="#{{country.id}}">{{country.name}}</div></li></ul>';
        $templateCache.put('templates/view1.html', tpl);
    }]);

    angular.module('templates/view2.html', []).run(["$templateCache", function ($templateCache) {
        var tpl = '<div>{{country.name}} clicks {{countCntry()}} <br> overall clicks {{countOverall()}}</div><button><a href="#">BACK</a></button><button ng-click="clickCnt()" >count clicks ++ </button>';
        $templateCache.put('templates/view2.html', tpl);
    }]);

【问题讨论】:

    标签: javascript html angularjs angularjs-scope


    【解决方案1】:

    问题在于您没有根据国家/地区增加计数。现在正在研究小提琴。

    编辑:

    我已经更新了小提琴:http://jsfiddle.net/1xtc0zhu/2/

    我所做的基本上是让 cntryCnt 成为一个对象字面量,它将国家/地区 ID 作为属性并保持每个 ID 的正确计数,如下所示:'

    var cnt      = 0;
    var cntryCnt = {};
    
    ...
    
    // The function now receives the country id and increments the specific country clicks only.
    var incCntryCount = function(id) {
           cntryCnt[id] = cntryCnt[id] || 0;
           cntryCnt[id]++;
           return cntryCnt[id];        
    }
    

    其余的更改在模板中,基本上只是在获取或增加计数时将国家/地区 ID 作为参数发送。

    另外,这不是一个 Angular 特定的问题,而是一个一般性的编程问题。

    【讨论】:

      猜你喜欢
      • 2016-08-05
      • 1970-01-01
      • 2018-03-29
      • 2013-03-08
      • 1970-01-01
      • 2019-09-09
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多