【问题标题】:How to get a single item from a GoInstant collection?如何从 GoInstant 集合中获取单个项目?
【发布时间】:2014-06-24 04:11:54
【问题描述】:

如何从 GoInstant GoAngular 集合中获取单个项目?我正在尝试为单个任务创建典型的显示或编辑屏幕,但我无法显示任何任务数据。

这是我的 AngularJS 控制器:

.controller('TaskCtrl', function($scope, $stateParams, $goKey) {

    $scope.tasks = $goKey('tasks').$sync();

    $scope.tasks.$on('ready', function() {
        $scope.task = $scope.tasks.$key($stateParams.taskId);
        //$scope.task = $scope.tasks.$key('id-146b1c09a84-000-0'); //I tried this too
    });
});

这里是对应的AngularJS模板:

<div class="card">
    <ul class="table-view">
        <li class="table-view-cell"><h4>{{ task.name }}</h4></li>
    </ul>
</div>

使用 {{ task.name }} 或通过引用任何任务的属性不会呈现任何内容。任何帮助将不胜感激。

【问题讨论】:

    标签: angularjs goinstant goangular


    【解决方案1】:

    您可能会处理以下任务:(a) 从集合中检索单个项目,以及 (b) 响应用户指示以不同方式更改应用程序状态。

    请记住,GoAngular model(由$sync() 返回)是一个对象,在待办事项集合的情况下,它可能看起来像这样:

    {  
        "id-146ce1c6c9e-000-0": { "description": "Destroy the Death Start" },
        "id-146ce1c6c9e-000-0": { "description": "Defeat the Emperor" }
    }
    

    当然,它也有许多方法,可以使用$omit 方法轻松剥离。

    如果我们想从已经同步的集合中检索单个项目,我们可以这样做 (plunkr):

    $scope.todos.$sync();
    
    $scope.todos.$on('ready', function() {
      var firstKey = (function (obj) {
        for (var firstKey in obj) return firstKey;
      })($scope.todos.$omit());
    
      $scope.firstTodo = $scope.todos[firstKey].description;
    });
    

    在本例中,我们同步集合,一旦它准备好检索集合中第一个项目的键,并将对该项目的引用分配给$scope.firstTodo

    如果我们要响应用户的输入,我们需要根据用户的交互将 ID 从视图传递回控制器。首先我们将更新我们的视图:

      <li ng-repeat="(id, todo) in todos">
          <a href="#" ng-click="whichTask(id)">{{ todo.description }}</a>
      </li>
    

    现在我们知道用户想要我们修改哪个待办事项,我们在控制器中描述该行为:

    $scope.todos.$sync();
    
    $scope.whichTask = function(todoId) {
      console.log('this one:', $scope.todos[todoId]);
    
      // Remove for fun
      $scope.todos.$key(todoId).$remove();
    }
    

    这是一个工作示例:plunkr。希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 1970-01-01
      • 2015-11-01
      • 2011-01-19
      • 2020-02-05
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      • 2016-05-16
      相关资源
      最近更新 更多