【问题标题】:Undefined resolved data while accessing nested view访问嵌套视图时未定义的解析数据
【发布时间】:2014-02-21 23:24:36
【问题描述】:

我尝试将 Firebase 集成到一个基于 UI-Router 示例的简单 AngularJS 项目中。

这似乎在使用导航流时效果很好......但实际上在使用例如直接 url 直接访问嵌套视图时得到了一个未定义的变量:#/contacts/42

您可以在以下 plunker 上测试并查看源代码: http://plnkr.co/edit/1CnwHl9rsOifzWoSYg8V?p=preview

正如您在 firebug 中看到的,我收到以下错误: 错误:contacts[i] 未定义

Contacts 是工厂 'ContactDB' 的一个变量,它由 firebase 后端承诺并解析状态 'contacts' 的数据。

$scope.contacts 似乎已损坏。只设置了第一项...

我真的不明白这个问题的原因......?!

如果有人可以帮助我,那就太好了。 提前感谢您查看。

【问题讨论】:

  • 即使关闭 Plnkr 也会出现此问题吗? (例如,当您在 localhost 上运行时)。
  • 是的,它发生在 Plunker 和 localhost...我不明白。

标签: angularjs firebase angular-ui-router


【解决方案1】:

我还在使用 ui-router 和 firebase,但在尝试获取要在状态路由更改时显示的联系人数量时遇到问题。我在联系人控制器中使用 numChildren()。

.controller( 'contactsCtrl', function contactsCtrl( $scope, filterFilter, orderByPriorityFilter, contacts, FBURL ) {
  var contactsRef = new Firebase(FBURL+'/contacts');
  $scope.entryLimit = 50;
  $scope.search = $scope.lastSearch.search;

  contactsRef.on('value', function(snap) {
    $scope.contacts = contacts;//contacts is a resolved $firebase Object
    $scope.contactsCount = snap.numChildren();
  });


  $scope.$watch('search', function(oldTerm, newTerm) {
    $scope.filtered = filterFilter(orderByPriorityFilter($scope.contacts), oldTerm);
    $scope.contactsCount = $scope.filtered.length;
    $scope.lastSearch.search = oldTerm;

    //sets contacts list page to 1 on new searches
    if (oldTerm != newTerm) {
      $scope.contactListPos.page = 1;
    }

  });

});

如果您从浏览器栏加载 /contacts 路由或刷新页面,这将正常工作。但是,如果我从我的 /home 状态更改状态,该状态有一个指向 /contacts 的链接,$scope.contactsCount 将显示 0。我在搜索输入中也有一个 $watch,只有当我进行搜索时,contactsCount 才会更新.当我进入 contacts.detail 子状态然后返回联系人状态时,contactsCount 也会正确更新。

我可以通过使用 if/else 语句编辑 $watch 回调来使其工作:

if (newTerm === oldTerm) { //first run
  return;
} else {
  $scope.contactsCount = $scope.filtered.length;
}

【讨论】:

  • 搜索输入中的 $watch 似乎将 $scope.contactsCount 设置回 0。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多