2017-04-17 72 views
0

目标:我希望$ scope.pluraliser在选择一年时返回随机值。 1966 目前如果多个值相同,它总是会选择最后一个值。使用Fisher耶茨随机阵列算法AngularJS如何从ng-pluralizer中获得随机值?

$ scope.pluralizer = {

1966 : "Something New !", 
    1966 : "Something Different!", 
    1966 : "Something Else", 
    1967 : "Something New !", 
    1967 : "Something Different!"', 
    1967 : "Something Else", 
    1968 : "Something New !", 
    1968 : "Something Different!", 
    1968 : "Something Else" 


    } 


You can randomise nested lists quite easily with ng-repeat 

http://jsfiddle.net/owenmead/fa4v8/1/ 

$ scope.list = [

'"1966" : "Something New !"', 
    '"1966" : "Something Different!"', 
    '"1966" : "Something Else"', 
    '"1967" : "Something New !"', 
    '"1967" : "Something Different!"', 
    '"1967" : "Something Else"', 
    '"1968" : "Something New !"', 
    '"1969" : "Something Different!"', 
    '"1970" : "Something Else"', 

] 
$scope.random = function() { 
    return 0.5 - Math.random(); 

    HTML 
    <p ng-repeat="i in list|orderBy:random">{{i}}</p> 

和随机化阵列如何可以随机化Pluralizer所以它会在选择一年后返回不同的/随机值?

回答

0

在您的pluralizer变量中,您正在覆盖“1966”的值。所以,当你定义3个值时,每个值都会覆盖前一个值。要解决这个

一种方法是多值存储在一个这样的数组:

$scope.pluralizer = { 
    1966 : ["Something New!", "Something Different!", "Something Else"],  
    1967 : ["Something New!", "Something Different!", "Something Else"], 
    1968 : ["Something New!", "Something Different!", "Something Else"] 
} 

有了这个,你可以得到数组1966年,然后随机选择阵列指标之一。不知道你想如何使用这个变量,所以我不会添加任何代码随机抽取值...