繁体   English   中英

Angular选择调用服务工厂函数(http)

[英]Angular select that calls service factory function (http)

简单的情况,我有一个服务来检索名为lists(<list_id>). 但我不明白如何自动调用该服务......

JS问我的问题

<select name='lists' 
   ng-model="list" 
   ng-options="t.title for t in lists._lists">
       <option value="">-- chose list --</option>
</select>
<h1>List was  -{{ list.title }}</h1>
<ul>
    <li ng-repeat="t in lists.lists(list)" class='task'>{{t.title}}: {{t.id}}</li>
 </ul>

主要服务

angular.module('service',['ngResource']).factory('List', function($http) {
  var List= function(data) {
#magic to build List from json
#save to ._lists
#or if just one build List
  }
  List.lists = function(list_id, query) {
    url = '/tasks/lists/';
    #if list_id is there use it else give all lists
    return $http.get(url).then(function(response) {
      return new List(response.data);
   });
 };

主要的

//this initially populates lists._lists with all the available lists
//it also has a List method on the object   
$scope.lists= List.lists();

当我更改选择时,我可以看到标题更新。 我的控制器有一个“列表”方法,它接受一个列表对象,并将执行查询,但它永远不会被调用。

关于我缺少什么的任何建议?

我认为最好对所选列表的更改做出反应然后查询服务。 否则,您将查询服务每个$ digest循环。

$scope.$watch('list', function(list) {
       $scope.tasks = List.lists(list).tasks;    });

更新了这个解决方案的小提琴: http//jsfiddle.net/4PZGs/1/

(但是没有对数据进行操作,但可能是一些更复杂的代码......)

您不能从模板中调用服务 - 而您也不希望因为这意味着您没有正确分离关注点。 解决方案是使用范围方法包装您的服务:

$scope.getList = function ( list ) {
    if ( ! angular.isDefined( list ) ) return;
    $scope.currentList = List.lists(list);
}

然后在模板中使用

<ul>
    <li ng-repeat="t in currentList" class='task'>{{t.title}}: {{t.id}}</li>
</ul>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM