3

我有指令,我在其中动态添加其他指令和属性:

app.directive('lrDatetime', function ($compile) {
return {
  restrict: 'AE',
  require: ["ngModel"],
  scope: {
    ngModel: "=",
    item: "="
  },
  templateUrl: "template.html",
  compile: function compile(element, attrs) {
    var datepicker = element.find(".lr-datepicker");

    if (attrs.required === "true") {
        datepicker.attr("ng-required", "true");
    }

    return {
        pre: function preLink(scope, iElement, iAttrs, controller) { },
        post: function postLink(scope, iElement, iAttrs, controllers) {
            $compile(iElement.contents())(scope);
        }
    };
  },
  controller: function ($scope) {
    $scope.opened = false;
      $scope.open = function ($event, obj, which) {
          $scope.opened = true;
      };

      $scope.format= "dd.MM.yyyy"; 

  }
};
});

和模板:

<input type="text" 
class="lr-datepicker" 
is-open="opened"  
uib-datepicker-popup="{{format}}"
datepicker-append-to-body="true"
ng-model="ngModel" />
<span class="input-group-btn">
    <button type="button" class="btn btn-default" 
    ng-click="open($event, item, 'isOpened')">
        Open
    </button>
</span>

现在,当我绑定了值并尝试在输入中输入内容时,它会被删除。我知道如果模型无效,角度将其设置为“未定义”,但如果我在指令之外执行相同操作,它会保留输入的内容。

如果我只是将这些属性移动到模板并删除对 $compile 的调用 - 一切都按预期工作。但是这种方法的巨大缺点是我无法控制属性外观,它总是会被渲染。

我错过了什么?

普朗克

4

1 回答 1

1

找到了解决方案 - ngModel 属性应该在 $compile 之前手动添加到链接函数中:

app.directive('lrDatetime', function ($compile) {
    return {
      restrict: 'AE',
      require: ["ngModel", "^form"],
      scope: {
        ngModel: "=",
        item: "=",
        required: "=",
        name: "@"
      },
      templateUrl: "template.html",
      link: function (scope, element, attrs, controllers) { 
        scope.itemForm = controllers[1];

        scope.opened = false;
        scope.open = function ($event, obj, which) { 
            scope.opened = true;
        };

        scope.format= "dd.MM.yyyy"; 

        var datepicker = element.find("input");

        if (scope.required === true) {
            datepicker.attr("ng-required", "true");
        }

        datepicker.attr("name", scope.name);
        datepicker.attr("ng-model", "ngModel");
        datepicker.attr("uib-datepicker-popup", scope.format);

        $compile(element.contents())(scope);

     }
  };
});

模板:

<input type="text" 
class="lr-datepicker" 
is-open="opened"  
datepicker-append-to-body="true" />    
<span class="input-group-btn">
    <button type="button" class="btn btn-default" 
    ng-click="open($event, item, 'isOpened')">
        Open
    </button>
</span>
<span ng-if="itemForm[name].$error.required">required!</span>

普朗克

认为问题之所以出现是因为模板被编译了两次并且模型被重新绑定。

于 2015-11-14T20:28:42.887 回答