使用AngularJS指令的部分应用功能不起作用

时间:2015-04-08 21:35:03

标签: javascript angularjs angularjs-directive angularjs-scope

我正在为文档的各个方面构建内联编辑器(想想标题,内容,标签等);但是,我遇到了一些问题。这里(有点)我的指令链接函数是什么样的:

var directive = {
  restrict: 'A',
  templateUrl: '/path/to/partial',
  transclude: true,
  scope: {
   save: '&',
   text: '='
  },
  link: link
};

return directive;

function link(scope, element, attrs) {
  scope.active = false;
  scope.edit = function() {
    scope.active = true;
  };

  scope.done = function() {
    scope.active = false;
  }

  scope.doneEditing = function() {
    scope.save(scope.text);
    scope.done();
  }
}

我正在传递save回调,通知家长要保存的内容和位置。现在,我决定构建一个返回函数(或部分应用程序/工厂模式)的函数,而不是传递描述属性的另一个prop(如“title”,“content”等):

scope.documentSave = function(key) {
   var update = {};
   return function(value) {
      update[key] = value;
      DocumentService
       .update(scope.document.id, update)
       .then(function() {})
      ;
   }
}

这是我的宣言:

<h1 inline-editor text="document.name" save="documentSave('name')">{{ document.name }}</h1>

实际上工作的奇怪之处在于将scope.save的调用更改为scope.save()(scope.text),这非常愚蠢。我也尝试在控制器中触发工厂而不是像这样查看:

$scope.documentSaveName = documentSave('name');

再次,wtf。使用scope.save()(scope.text)运行它使其工作但常规scope.save(scope.text)没有(它应该)。再次,wtf。

我控制台。忘记了scope.save并得到了这个:

function(locals) {
  return parentGet(scope, locals);
}

我之前从未遇到过这种行为,而且我已经使用了很多指令和回调。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

据我所知,当你使用&将值绑定到你的指令范围时,得到的是包含在函数中的值(如getter),以便它只有一个三通。

因为documentSave函数的返回值本身就是一个函数,所以得到的函数包含在函数中,因此需要执行$scope.save()(scope.text)