0

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 ?

1
  • if you can share jsfiddle then it would be better !! Commented Jan 26, 2013 at 20:01

2 Answers 2

2

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...)

Sign up to request clarification or add additional context in comments.

1 Comment

This worked out, my fiddle example was grossly simplified. Thanks again.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.