1

I have an object that contains a resource. When I use this resource to make requests in most parts of an application, and it works fine. However, inside of a function that gets called due to an event in a directive (jQuery draggable and droppable, event fires when an element is dropped), the resource will not fire a request. Why is this? Is there a workaround or fix?

Example:

  //function called by directive
  Project.appendTemplate = function(project, tID) {
    console.log('appendTemplate Called'); //this happens
    Template.resource.get({'ID' : 1}, function(result) {
      console.log('hello'); //this does not
    });
  }

  //called when this service is loaded
  Template.resource.get({'ID' : 1}, function(result) {
    console.log('hello'); //happens
  });
GSto
  • 41,512
  • 37
  • 133
  • 184

1 Answers1

0

You need to wrap your event handler code in a call to scope.$apply() or $scope.$apply (depending whether you are in the link or controller method of the directive) like so:

Project.appendTemplate = function(project, tID) {
    scope.$apply(function(){
        console.log('appendTemplate Called'); //this happens
        Template.resource.get({'ID' : 1}, function(result) {
            console.log('hello'); //this does not
        });
    });
}

Whenever such a change occurs from outside of the Angular framework in an event callback, $apply() tells Angular about that change.

See this answer for more.

Community
  • 1
  • 1
Dan
  • 59,490
  • 13
  • 101
  • 110
  • `scope.$apply()` is used if you need to update a model within Angular from outside of the framework. It is not necessary for things like triggering a `$http` request. – rtcherry Jun 11 '13 at 01:20
  • @rtcherry I guess I'm making a little bit of an assumption that he wants to do more than just log something with the `result` from the callback. He may have replaced code that was there with the log to shorten his post. Imagine that he modifies the model in some way instead of logging 'hello', then `$apply` will be needed. – Dan Jun 11 '13 at 02:08