如何使用AngularJS在Array中存储变量?

时间:2016-02-25 09:51:56

标签: javascript angularjs

我可以使用任何功能吗?

或者我需要创建一个?或者我可以使用推?它是从此页面修改的脚本: http://code-maven.com/automatic-counter-using-angularjs

   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>

<script>
    angular.module('CounterApp', [])
            .controller('CounterController', function($scope, $timeout) {
                var timer;
                $scope.stored = [];
                $scope.counter= 0;

                $scope.stopCounter = function() {
                    $timeout.cancel(timer);
                    timer = null;
                };
                $scope.startCounter = function() {

                    if (timer === null) {
                        updateCounter();
                    }
                    $scope.stored.push(counter);
                };

                $scope.pushedVariable = function() {
                    $scope.stored.push(counter);
                };
                var updateCounter = function() {
                    $scope.counter++;
                    timer = $timeout(updateCounter, 1000);

                };

                $timeout.cancel(timer);
                timer = null;
            });
</script>
<div ng-app="CounterApp">
    <div ng-controller="CounterController">

        <button ng-click="stopCounter()">Stop</button>
        <button ng-click="startCounter()">Start</button>
        <button ng-click="pushedVariable()">Push</button>
        {{counter}}
        <p>Stored Variable 1: {{stored[0]}}</p>
        <p>Stored Variable 2: {{stored[1]}}</p>
    </div>
</div>

2 个答案:

答案 0 :(得分:3)

您只需在函数中使用$scope.stored.push($scope.counter);而不是当前$scope.stored.push(counter);这是一个未定义的变量。

答案 1 :(得分:1)

function(obj){         var str = [];         for(var val in obj)         str.push(encodeURIComponent(val)+“=”+ encodeURIComponent(obj [val])); }

“obj”是你的对象。