如何将AngularJS范围对象转换为简单的JS数组?

时间:2016-07-11 10:29:07

标签: javascript html angularjs

如何将AngularJS范围对象转换为简单的JS数组?

此函数检查是否选中了任何复选框,并将相应的值添加到对象。 现在我想将对象值传输到一个数组,并在按下按钮后发出警报。但结果是未定义的,为什么?

var formApp = angular.module('formApp', [])

    .controller('formController', function($scope) {

        // we will store our form data in this object
        $scope.formData = {};
        

    });

var array = Object.keys(formData).map(function(k) { return obj[k] });

function test(){

alert(array);
}
<-- index.html -->
<!DOCTYPE html>
<html>
<head>

    <!-- CSS -->
    <!-- load up bootstrap and add some spacing -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <style>
        body         { padding-top:50px; }
        form         { margin-bottom:50px; }
    </style>

    <!-- JS -->
    <!-- load up angular and our custom script -->
    <script src="http://code.angularjs.org/1.2.13/angular.js"></script>
    <script src="app.js"></script>
</head>

<!-- apply our angular app and controller -->
<body ng-app="formApp" ng-controller="formController">
<div class="col-xs-12 col-sm-10 col-sm-offset-1">

    <h2>Angular Checkboxes </h2>

  
...

    <!-- MULTIPLE CHECKBOXES -->
    <label>Favorite Colors</label>
    <div class="form-group">
        <label class="checkbox-inline">
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red"> Red
        </label><br>
        <label class="checkbox-inline">
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.blue"> Blue
        </label> <br>
        <label class="checkbox-inline">
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.green"> Green
        </label>
    </div>

...
    
    <!-- SHOW OFF OUR FORMDATA OBJECT -->
    <h2>formData_object_is_not_empty-test</h2>
    <pre>
       {{formData}}
    </pre>
     <button onclick="test()">Click me</button> 
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

试试这个:

var formApp = angular.module('formApp', [])

.controller('formController', function($scope) {

    // we will store our form data in this object
    $scope.formData = {};
    var array = Object.keys($scope.formData).map(function(k) { return obj[k] });
    // wait for the formData to change and then alert
    setTimeout(function() {
        alert(array);
    }, 2000);


});

Angular的制作方式是不允许您访问控制器外部的范围变量。

如果您希望将数组作为调试信息,请使用AngularJS Batarang之类的浏览器插件或使用console.log(array)代替alert(array)或尝试使用{{将数组保存在全局变量中1}},所以你可以在浏览器控制台中访问它。