2014-11-06 44 views
0

好吧,试着做我应该是一件简单的事情,我需要使用ng-repeat和assocative数组。完全失去了为什么这不起作用。它完全适用于基于数字的数组键,但不能使用文本字符。ng-repeat与关联数组

function HelloCntl($scope) { 
    $scope.friends = []; 
    $scope.friends[0] ='John', 
    $scope.friends[1]= 'Mary', 
    $scope.friends['aksnd']= 'Mike', 
    $scope.friends['alncjd']= 'Adam', 
    $scope.friends['skdnc']= 'Julie' 
} 

---- 

<div ng-controller="HelloCntl"> 
<ul> 
    <li ng-repeat="friend in friends"> 
     <span>{{friend}}</span> 
    </li> 
</ul> 
</div> 

我也放在一起,这是小提琴显示发生了什么 http://jsfiddle.net/b9g0x7cw/4/

我在做什么错在这里?我错过了明显的东西吗?

谢谢你们!

回答

3

在JavaScript中,我们没有关联数组 - 我们有对象:

更新小提琴:http://jsfiddle.net/edut808r/

angular.module('MyApp', []).filter('removeAdam', function() { 

}) 
.controller('HelloCntl', function($scope) { 
    $scope.friends = { 
     asdf:'John', 
     dkfls: 'Mary', 
     aksnd: 'Mike', 
     alncjd: 'Adam', 
     skdnc: 'Julie' 
    } 
}); 
+0

是的,我一直都知道,但从来没有真正钻研的差异,一些研究之后,我意识到,assocative阵列是一种没有没有(http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful /),并使用对象表示法代替。很高兴知道!我从来没有意识到关联数组的数组长度是0,这就是为什么当我大吼大叫时,角度看着我很奇怪。 – Justin 2014-11-06 14:40:56

0

不要使用关联数组!

http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/

2个BIG理由不使用关联数组

  • 它们具有0
  • 您实际上是在编辑阵列对象的属性,而不是阵列的长度键。

http://jsfiddle.net/3kppwhh6/1/

// using array 
var friendsArr = []; 
friendsArr['one']='one'; 
friendsArr['two']= 'two'; 

friendsArr.length; // 0 
Object.keys(friendsArr).length; //2 

//Using object 
var friendsObj = {}; 
friendsObj['one'] ='one'; 
friendsObj['two'] = 'two'; 

Object.keys(friendsObj).length; //2