【问题标题】:How can I loop through a firebase collection and add a unique color to each?如何循环遍历一个 firebase 集合并为每个集合添加独特的颜色?
【发布时间】:2015-01-15 02:32:53
【问题描述】:

我正在尝试遍历用户配置文件并为每个人分配唯一的颜色。这是我到目前为止所拥有的:

更新:我可以遍历 $scope.profiles 并单独访问每个配置文件。我无法弄清楚如何将颜色数组中的唯一颜色添加到每个配置文件。

 var colors  = ['red', 'blue', 'green', 'purple', 'orange', 'teal', 'violet', 'burgandy', 'brown', 'pink'];

 var obj = $firebase(new Firebase('https://demo.firebaseio.com/' + team + '/profiles')).$asObject();

 obj.$loaded().then(function() {
  var i = 0;
    angular.forEach(obj, function(value, key) {
      //how do I add a color from the colors array?
      value.$add(colors[i++]);
    });
 });

【问题讨论】:

    标签: javascript jquery angularjs firebase


    【解决方案1】:

    试试这样的:

    var ind = 0;
    
    $.each($scope.profiles, function (i, e){
      if (e && e.username){
          e.colour = colors[ind++]
      }
    });
    

    更新

    如果$scope.profiles 是一个承诺,这样的事情可能会起作用:

    var ind = 0;
    
    $.when($scope.profiles).done(function(obj){
        $.each(obj, function (i, e){
            if (e && e.username){
                e.colour = colors[ind++]
            }
        });
    }); 
    

    这是有效的确切解决方案。

    // to take an action after the data loads, use $loaded() promise
         $scope.profiles.$loaded().then(function() {
           var i = 0;
            angular.forEach($scope.profiles, function(value, key, profile) {
              value.color = colors[i++];
              profile.$save();
            });
         });
    

    【讨论】:

    • 在firebase中设置颜色似乎不起作用。我将其更新为 angular.forEach。这个问题至少在某种程度上与 $scope.profiles 是一个承诺有关。
    • 有没有等价于.when的angularjs。我可以试试 $loaded 吗?
    • 我将其修改为: $scope.profiles.$loaded().then(function(obj){ angular.forEach(obj, function (i, e){ if (e && e.用户名){ e.colour = colors[ind++]; } }); });但这似乎不起作用。我正在尝试深入研究以找出原因,但目前还不清楚。
    • @EmptyPockets 看看github.com/firebase/angularfire/issues/377 有代码var obj = $firebase(new Firebase(URL)).$asObject(); obj.$loaded().then(function() {
    • @EmptyPockets 最简单的方法可能是在循环中使用 var ind = 0 变量。如果您的配置文件多于颜色,您可以这样做e.colour = colors[(ind++) % colors.length]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2016-07-16
    • 2014-08-13
    相关资源
    最近更新 更多