【问题标题】:Angular select that calls service factory function (http)调用服务工厂函数(http)的角度选择
【发布时间】:2013-01-26 19:30:17
【问题描述】:

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

JS Fiddle of my issue

<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);
   });
 };

主要js

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

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

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

【问题讨论】:

  • 如果你能分享jsfiddle那就更好了!!

标签: angularjs


【解决方案1】:

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

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

使用此解决方案更新小提琴:http://jsfiddle.net/4PZGs/1/

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

【讨论】:

  • 这成功了,我的小提琴示例被大大简化了。再次感谢。
【解决方案2】:

您不能从模板调用服务 - 您也不想这样做,因为这意味着您没有适当的关注点分离。解决方案是使用范围方法包装您的服务:

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

然后在你的模板中使用 that

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 2016-07-20
    • 1970-01-01
    • 2017-05-26
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多