2014-11-03 67 views
2

我有以下服务的功能,将返回的数据,这是我想显示(注意,该数据可以随时改变):AngularJS:最佳实践将数据传递到模板

myService.getData(); // Returns an array 

我有使用服务,因为我也需要这些数据在其他控制器/服务中。

现在我不确定,最好的实践是什么,也将数据显示在模板中。我所做的,就是:

例1

<li ng-repeat="item in myService.getData()"> 
    {{item.name}} 
</li> 

它的做工精细,但它是最好的做法?

我也尝试以下操作:

例2

// In my controller: 
$scope.data = myService.getData(); 

// In the template 
<li ng-repeat="item in data" ng-controller="myCtrl"> 
    {{item.name}} 
</li> 

这不起作用(在页面上加载的数据是获得一次到$ scope.data任何更新都将被忽略)。我想我可以使用$ watch(观看myService.getData())。但是我猜这比较慢。

您认为如何?我可以在模板中调用服务吗(如示例1)?

非常感谢!

+0

的'getData'方法的代码片段将是有益的 – 2014-11-03 15:49:39

回答

0

以此作为第二个例子(最佳实践):

// In my controller: 
$scope.service= myService 

// In the template 
<li ng-repeat="item in service.getData()" ng-controller="myCtrl"> 
    {{item.name}} 
</li> 
+0

是的,这是(已经)我使用的到底是什么。我只是不确定这是否有效,或者我必须使用一些不同的方法。 – Tream 2014-11-03 15:52:19

+0

这是最好的做法。你可以毫无疑问地使用它。 – 2014-11-03 15:53:56

+2

@MukundKumar是什么让你觉得这是最佳做法?什么是'getData'使得AJAX请求,然后它将在每个摘要循环中被执行多次? – dfsq 2014-11-03 15:58:59