Nix
Nix

Reputation: 58572

Angular select that calls service factory function (http)

Simple situation, I have a service to retrieve a list called lists(<list_id>). But I dont understand how to automatically call that service...

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>

main service

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

main js

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

When I change the select I can see title update. My controller has a "lists" method that takes in a list object, and will do the query but it never gets called.

Any suggestions on what I am missing ?

Upvotes: 0

Views: 1843

Answers (2)

Valentyn Shybanov
Valentyn Shybanov

Reputation: 19391

I think it is better to react on change of selected list and then query service. Otherwise you would query service each $digest loop.

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

Updated fiddle with this solution: http://jsfiddle.net/4PZGs/1/

(But did't got your manipulations with data, but may be that was piece of some more complex code...)

Upvotes: 2

Josh David Miller
Josh David Miller

Reputation: 120513

You cannot call a service from a template - and you wouldn't want to as that would mean you don't have proper separation of concerns. The solution is to wrap your service with a scope method:

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

And then use that in your template:

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

Upvotes: 0

Related Questions