2013-01-05 119 views
4

我有一个简单的应用程序,其中列出接触报告, 在里面我做了从Mongolab获取数据的列表视图。如何刷新视图无需刷新页面在angularjs应用

在那我还做了一个输入表单提交

我在控制器中使用函数从角的例子为蓝本在其网站上时,使列表中的一个新的联系人报告:

app.factory('Contact',function($mongolabResource){ 
    return $mongolabResource('contacts'); 
}); 

function ContactCreateCtrl($scope,$location,Contact) { 
Contact.save(contact,function(){ 
     $location.path('/'); 
    }); 
}; 

$ location.path()是重新加载页面的回调。

当数据被提交(.save()是成功的)视图重载无刷新页面我如何重写这个让?

我尝试删除,然后重新定义数组,但似乎没有工作:

Contact.save(contact,function(){ 
     delete $scope.contacts; 
     $scope.contacts = Contact.query(); 
    }); 

我想实现这个的删除功能以及。有人能指出我在哪里可以学到这一点吗?

任何帮助

+0

为什么你需要重新加载视图? –

+0

所以我的列表显示了新添加的项目,现在它通过执行$ location.path()来实现它。如果我删除列表不会更新,但当我手动重新加载浏览器,它显示新项目 –

+0

即时通讯更顺畅的应用程序体验没有页面重新加载 –

回答

9

好吧,我更新了你的小提琴从数据库中获取的值:http://jsfiddle.net/joshdmiller/Y223F/2/

app.controller('MainCtrl', function ($scope,Contact) { 
    $scope.updateContacts = function() { 
    Contact.query(function(data) { 
     $scope.contacts = data; 
    }); 
    }; 

    $scope.save = function(newContact) { 
    Contact.save(newContact, function() { 
     $scope.updateContacts(); 
    }); 
    }; 

    // The initial data load 
    $scope.updateContacts(); 
}); 

有两点需要注意:

(1)我把你的蒙戈查询到功能,使得它可以被称为当再次创造了新的记录;

(2)$ mongolabResource预计要在成功执行的回调;你的应用程序闪烁,因为你没有提供。换句话说,从您调用查询到完成时间获取的时间,您的列表是空的。相反,我们希望它在我们获得新数据时仅更改。我也改变了。

在手动添加项目或从数据库中获取的方面,最好的做法是根据使用情况和存在权衡。但对于这样的小数据,只需从数据库中获取。

+0

啊我看到了,没有跨越我的想法,使其功能。 thx Josh –

+0

@MarkRajcok我知道它的工作原理;但正如我所说,它会导致闪烁。这是与删除回调和直接分配的值相同的小提琴:http://jsfiddle.net/joshdmiller/Y223F/3/。直接分配对于初始检索可能是一个有用的技巧,但除此之外,它会降低用户体验。 –

+0

对不起@Josh,我没有仔细阅读你的答案。我删除了我的评论(在您回复之前)。你拥有的肯定更好(+1)。 –

0

,不胜感谢得到这个工作,但仍不能确定推到数组的范围,效果会更好,如果我们能够从数据库

function ContactCreateCtrl($scope,$location,Contact) { 
    Contact.save(contact,function(){ 
    $scope.contacts.push(contact); 
}); 

另外我想取需要由db自动生成的_id对象,用于链接目的。这种方法不给我的_id,任何见解?

0

我分享我的答案我如何使用火力身份验证服务标志清除后的数据视图出从火力点。登录方法呼叫$scope.currentUser = null;后,数据仍然存在。必须重新加载以查看数据更改。不是最好的UX。

$scope.getCurrentUser = function() { 
     firebase.auth().onAuthStateChanged(function(user) { 
      if (user) { 
       // User is signed in. 
       $scope.currentUser = user; 
      } else { 
       // No user is signed in. 
       $scope.currentUser = null; 
       console.log('user not signed in.'); 
      } 
     }); 
    } 

$scope.getCurrentUser(); 


$scope.signout = function() { 
     firebase.auth().signOut().then(function() { 
      // Sign-out successful. 
      console.log('signed out success'); 
      $scope.getCurrentUser(); 
     }, function(error) { 
      // An error happened. 
      console.log(error); 
     }); 

    } 

所以调用getUserData方法和使currentUser = NULL有更新,而不重新加载的图。这是一个使用Firebase的例子,但只需稍作调整,它可能适用于从视图中清除数据而无需整页重新加载的需求。Firebase在这里完成了清除用户对象的工作,但我的视图并不关心,直到再次检查我的getCurrentUser方法以查看是否仍有用户,如果不是,则在$ scope中清除它而不重新加载视图。