简体   繁体   English

将范围值加载到数组中在angularjs中不起作用

[英]loading scope value into an array doesnt work in angularjs

Please consider the small angularJs code snippet below.

$scope.myArray = [];
function sampleMethod(){
    $scope.myArray.push({
        name: $scope.name,
        age: $scope.age
    });
    console.log($scope.myArray.name);
};

Here, I was trying to get the scope values name and age and loading it to a scope array inside a controller. 在这里,我试图获取范围值name和age并将其加载到控制器内的范围数组中。 But the above program prints nothing. 但是上面的程序什么都没打印。 Cant we access and feed scope values to an array from controller? 我们不能从控制器访问并将范围值提供给数组吗? If not possible, how can I do it correctly? 如果不可能,我该怎么做才能正确?

Your $scope.myArray is an array, not an object. $ scope.myArray是一个数组,而不是一个对象。

DO this, $scope.myArray[0].name it should work. 这样做, $ scope.myArray [0] .name它应该工作。

Try like this: 试试这样:

 var app = angular.module('app', []); app.controller('MainController', function($scope) { $scope.name = 'Cuco Pérez'; $scope.age = 37; $scope.myArray = []; (function sampleMethod() { $scope.myArray.push({ name: $scope.name, age: $scope.age }); console.log($scope.myArray[0].name); })(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="MainController"> <h1>Hi, my name is: {{ myArray[0].name }}</h1> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM