0

我编写了以下 Angular 指令:

angular.module('solarquote.directives', []).directive('editfield', function() {
return {
    restrict: 'A',
    transclude: true,
    template: '<span ng-hide="editorEnabled" ng-transclude></span>' +   // viewable field
  '<span ng-show="editorEnabled"><input class="input-medium" ng-model="editableField"></span>', // editable field
    link: function(scope, elm, attrs, ctrl) {
        scope.editorEnabled = false;
        scope.editableField = elm.children[0].children[0].innerText;
     }
  };
})

在 html 中,在 ng-repeat 中:

<span editfield>{{ item.fields.name }}</span>

我想用 ng-transclude 中的相同内容预填充指令模板中的输入字段。遍历 DOM 并获取文本会产生:{{ item.fields.name }} 而不是呈现的数据:“Bob”(或任何名称)。

访问嵌入数据的最佳方式是什么?

谢谢

4

1 回答 1

2

无法分配给ng-model您在嵌入块中指定的表达式。这是因为嵌入块可以是类似{{ functionValue() }}or的表达式{{ field1+':'+field2 }}。Angular 根本不知道如何反转这些表达式。

您可以做的是提供对要更新的模型的参考。请参阅以下 punkler http://plunker.co/edit/NeEzetsbPEwpXzCl7kI1?p=preview(需要 jQuery)

directive('editfield', function() {

  var template = ''+
    '<span ng-show="editorEnabled"><input class="input-medium" ng-model="editfield"></span>'+
    '<span ng-hide="editorEnabled" ng-transclude></span>';

  return {
    restrict: 'A',
    template: template,
    scope:{
      editfield:'='
    },
    transclude:true,
    link: function(scope, element, attrs) {
      var input = element.find('input');
      input.on('blur',function(){
        scope.editorEnabled=false;
        scope.$apply();
      });
      element.bind('click',function(){
        scope.editorEnabled=!scope.editorEnabled;
        scope.$apply();
        input.focus();
      })
     }
  };
})
于 2013-06-20T23:52:06.997 回答