将参数传递给Ressource的方法回调

时间:2016-02-03 14:07:24

标签: javascript angularjs api crud angular-resource

如果我在API中成功更新某些内容,我正在尝试更改一些模型数据:

this.saveProject = function(project) {
  var editedProjectSupport = {
        /* some data */
  };
  SupportTimeTracks.update({id: project.backendId}, editedProjectSupport,
    function() {
      // There :
      project.department = controllerScope.edit.project.department;
      project.timetrack = controllerScope.edit.project.timetrack;
      growl.success('Project support successfully edited');
    },
    function(result) {
      growl.error('Project support couldn\'t be edited.');
      console.log(result);
    });
  this.edit.project = {};
  $scope.$broadcast('edit.project');
};

但我在成功回调project中无法访问function()。无论如何都要在参数或其他内容中传递它。

如何更新我的project.department& project.timetrack

从视图中调用该函数,project在函数中是局部的(尽管它引用了作用域中的元素)

1 个答案:

答案 0 :(得分:0)

this.saveProject = function(project) {

  SupportTimeTracks.update({id: project.backendId}, editedProjectSupport,
    function() {
      // There : if you are not *shadowing* project variable, you MUST have access to project variable.
    }
  );
};

你的函数是一个闭包,projectthis.saveProject中定义的变量,所以如果你没有在同一个名字里面定义另一个变量(阴影你的第一个变量)project必须定义,并且您已将值传递给this.saveProject,而 可以访问它。

代码示例:

var closure = function(project){
  // I grab project var here
  setTimeout(function(){
    alert('there is no project shadowing: '+ project);
  }, 100);
};

closure('my project var');

var closureWithShadowing = function(project){
  // I grab project var here ... but
  setTimeout(function(){
    var project = 'I eat project variables'; // I have created a new var with the same name
             // so, I'm shadowing the original one.
    alert('project shadowing: '+ project);
  }, 500);
};

closureWithShadowing('my project var');