javascript - 尝试创建按日期排序的数组时,无法设置未定义错误的 "something"属性。

标签 javascript angularjs firebase

我发布了相关问题here on Stack Overflow @Kato 帮我找到了答案。我正在尝试实现他的答案,但收到错误“无法设置未定义的“某物”的属性”。

我做了一个尽可能详细的plnkr:http://plnkr.co/edit/M4zEjpZ4kqTKn1sHHMt6

//controller
angular.module('app').controller('DemoCtrl', function($scope, DatedList) {
  $scope.world = 'world';

  var listRef = new Firebase("https://talllly.firebaseio.com/");
  $scope.weeks = DatedList(listRef);

  $scope.addTask = function(){
    listRef.push({    
      text: $scope.task.text,
      week: 40,
      day: 2  
    });   
  };


});       

angular.module('app').service('DatedList', function($timeout) {
  return function(pathToList) {
    var list = {};  

    pathToList.on('child_added', function(snap) {
      $timeout(function() { // force Angular to run $digest when changes occur
        var data = snap.val();
        console.log(data);
        var week_number = data.week;
        var week_day = data.day;
        list[week_number][week_day] = data;
      });
    });

    //todo: write similar processing for child_changed and child_removed

    return list;
  }  
});

//html
<form ng-submit="addTask()">
      <input placeholder="add task" ng-model="task.text">
    </form>
    <div ng-repeat="(week, days) in weeks">    
     <h1>{{week}}</h1>
     <div ng-repeat="(day, items) in days">
        <h2>{{day}}</h2>
        <div ng-repeat="item in items">
           {{item|json}}
        </div>
     </div>
    </div>

最佳答案

您需要初始化list[week_number]:

pathToList.on('child_added', function(snap) {
  $timeout(function() { // force Angular to run $digest when changes occur
    var data = snap.val();
    console.log(data);
    var week_number = data.week;
    var week_day = data.day;

    list[week_number] = {};  // <- Add this line here
    list[week_number][week_day] = data;
  });
});

关于javascript - 尝试创建按日期排序的数组时,无法设置未定义错误的 "something"属性。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25986646/

相关文章:

firebase - Firebase 托管的身份验证

javascript - react ;访问对象内的字段

javascript - 链接到特定幻灯片

javascript - 表单验证删除 ng-model 对象?

android - 如何使用 Firebase 在 Android 中解决 Deep Link Enable

firebase - 我想从 flutter 中数组内部的 map 中读取数据

javascript - 从本地主机加载 json

javascript - 使用reactive.js 将 JSON 数据/对象发布到 API

html - angularjs 中的登录服务实现不起作用

javascript - 带有键事件处理程序的 Karma 单元测试 Angular Directive(指令)