为什么这个angularJS资源不会在事件中触发?

时间:2013-06-11 00:34:35

标签: javascript angularjs angularjs-directive

我有一个包含资源的对象。当我使用此资源在应用程序的大多数部分发出请求时,它工作正常。但是,在由于指令中的事件(jQuery draggable和droppable,在删除元素时触发事件)而调用的函数内部,资源不会触发请求。为什么是这样?有解决方法或修复方法吗?

示例:

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

1 个答案:

答案 0 :(得分:0)

您需要将事件处理程序代码包装在对scope.$apply()$scope.$apply的调用中(取决于您是否在指令的链接或控制器方法中),如下所示:

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

每当在事件回调中从Angular框架外部发生此类更改时,$apply()会告知Angular该更改。

See this answer了解更多信息。