【问题标题】:accessing items in firebase访问firebase中的项目
【发布时间】:2014-04-18 22:31:28
【问题描述】:

我正在尝试通过扩展应用程序以使用 firebase 作为后端来学习 firebase/angularjs。

我的锻造是这样的

.

在我的程序中,我已将firebaseio.com/projects 绑定到$scope.projects

我如何访问孩子? 为什么$scope.projects.getIndex()不把钥匙还给孩子们?

我知道这些项目在 $scope.projects 中,因为如果我这样做 console.log($scope.projects) 就可以看到它们

app.js

angular.module('todo', ['ionic', 'firebase'])
/**
 * The Projects factory handles saving and loading projects
 * from localStorage, and also lets us save and load the
 * last active project index.
 */
.factory('Projects', function() {
  return {
    all: function () {
      var projectString = window.localStorage['projects'];
      if(projectString) {
        return angular.fromJson(projectString);
      }
      return [];
    },
    // just saves all the projects everytime
    save: function(projects) {
      window.localStorage['projects'] = angular.toJson(projects);
    },
    newProject: function(projectTitle) {
      // Add a new project
      return {
        title: projectTitle,
        tasks: []
      };
    },
    getLastActiveIndex: function () {
      return parseInt(window.localStorage['lastActiveProject']) || 0;
    },
    setLastActiveIndex: function (index) {
      window.localStorage['lastActiveProject'] = index;
    }
  }
})

.controller('TodoCtrl', function($scope, $timeout, $ionicModal, Projects, $firebase) {

  // Load or initialize projects
  //$scope.projects = Projects.all();
  var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
  var projectRef = new Firebase(projectsUrl);
  $scope.projects = $firebase(projectRef);
  $scope.projects.$on("loaded", function() {
    var keys = $scope.projects.$getIndex();
    console.log($scope.projects.$child('-JGTmBu4aeToOSGmgCo1'));

    // Grab the last active, or the first project
    $scope.activeProject = $scope.projects.$child("" + keys[0]);
  });

  // A utility function for creating a new project
  // with the given projectTitle
  var createProject = function(projectTitle) {
    var newProject = Projects.newProject(projectTitle);
    $scope.projects.$add(newProject);
    Projects.save($scope.projects);
    $scope.selectProject(newProject, $scope.projects.length-1);
  };



  // Called to create a new project
  $scope.newProject = function() {
    var projectTitle = prompt('Project name');
    if(projectTitle) {
      createProject(projectTitle);
    }
  };

  // Called to select the given project
  $scope.selectProject = function(project, index) {
    $scope.activeProject = project;
    Projects.setLastActiveIndex(index);
    $scope.sideMenuController.close();
  };

  // Create our modal
  $ionicModal.fromTemplateUrl('new-task.html', function(modal) {
    $scope.taskModal = modal;
  }, {
    scope: $scope
  });

  $scope.createTask = function(task) {
    if(!$scope.activeProject || !task) {
      return;
    }
    console.log($scope.activeProject.task);
    $scope.activeProject.task.$add({
      title: task.title
    });
    $scope.taskModal.hide();

    // Inefficient, but save all the projects
    Projects.save($scope.projects);

    task.title = "";
  };

  $scope.newTask = function() {
    $scope.taskModal.show();
  };

  $scope.closeNewTask = function() {
    $scope.taskModal.hide();
  };

  $scope.toggleProjects = function() {
    $scope.sideMenuController.toggleLeft();
  };


  // Try to create the first project, make sure to defer
  // this by using $timeout so everything is initialized
  // properly
  $timeout(function() {
    if($scope.projects.length == 0) {
      while(true) {
        var projectTitle = prompt('Your first project title:');
        if(projectTitle) {
          createProject(projectTitle);
          break;
        }
      }
    }
  });

});

我对底部的对象感兴趣

console.log($scope.projects)

更新 在挖掘之后似乎我可能错误地访问了数据。 https://www.firebase.com/docs/reading-data.html

这是我的新方法

  // Load or initialize projects
  //$scope.projects = Projects.all();
  var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
  var projectRef = new Firebase(projectsUrl);

  projectRef.on('value', function(snapshot) {
    if(snapshot.val() === null) {
      console.log('location does not exist');
    } else {
      console.log(snapshot.val()['-JGTdgGAfq7dqBpSk2ls']);
    }
  });

  $scope.projects = $firebase(projectRef);
  $scope.projects.$on("loaded", function() {
    // Grab the last active, or the first project
    $scope.activeProject = $scope.projects.$child("a");
  });

我仍然不确定如何以编程方式遍历密钥,但我觉得我快接近了

【问题讨论】:

    标签: angularjs firebase ionic-framework


    【解决方案1】:

    这是一个包含更多对象的对象,用for in循环它:

    for (var key in $scope.projects) {
        if ($scope.projects.hasOwnProperty(key)) {
            console.log("The key is: " + key);
            console.log("The value is: " + $scope.projects[key]);
        }
    }
    

    【讨论】:

    • 嗯,不。它确实是一个具有键和值的对象。但我只对火力基地中对象的“孩子”键感兴趣。
    【解决方案2】:

    好的,所以val() 返回一个对象。为了遍历projects的所有孩子我做

      // Load or initialize projects
      //$scope.projects = Projects.all();
      var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
      var projectRef = new Firebase(projectsUrl);
    
      projectRef.on('value', function(snapshot) {
        if(snapshot.val() === null) {
          console.log('location does not exist');
        } else {
          var keys = Object.keys(snapshot.val());
          console.log(snapshot.val()[keys[0]]);
        }
      });
    
      $scope.projects = $firebase(projectRef);
      $scope.projects.$on("loaded", function() {
        // Grab the last active, or the first project
        $scope.activeProject = $scope.projects.$child("a");
      });
    

    注意var keys = Object.keys() 获取firebaseio.com/projects 的所有密钥,然后您可以通过snapshot.val()[keys[0]) 获取第一个孩子

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 1970-01-01
      • 2021-01-30
      • 2020-08-20
      • 2017-03-09
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      相关资源
      最近更新 更多