1

我正在尝试编写一个可配置的指令,该指令应用于需要 ngModel 的输入元素,并为 ngModel 添加解析器和格式化程序函数。

我遇到的问题是我似乎无法将插值传递到指令中,同时支持 ngModel 绑定。例如,我希望能够以两种方式之一使用我的指令:

传递文字参数:

<input ng-model="foo" my-directive="120" />

或从当前范围传递插值参数:

<input ng-model="foo" my-directive="{{bar}}" />

...
function MyCtrl($scope) {
  $scope.bar = "120";
}

如果我在指令定义中读取链接函数的属性参数,我可以在第一次使用中获取 attributes.myDirective 的值,但在第二次使用中 myDirective 的值是未定义的。

现在,如果我在指令定义中添加一个隔离范围:

scope: { myDirective: '@' }

然后在上面的场景中定义并插值了 scope.myDirective,但是现在 ngModel 坏了。我的解析器/格式化程序函数的输入参数未定义。发生了什么事,我该如何实现我想要的行为?

指示:

module.directive('myDirective', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            replace: false,
            link: function (scope, elm, attrs, ctrl) { // attrs.myDirective not interpolated
4

1 回答 1

2

添加隔离范围时,您正在创建全新的子范围,它不会从具有ngModel' 值的范围继承。这就是为什么您的解析器和格式化程序变得不确定的原因。

此外,在您的示例中,要获得 的值bar,您不需要在花括号中使用它:

<input ng-model='foo' my-directive='bar' />

在您的链接功能中:

link: function(scope, element, attr, ctrl) {
  attr.myDirective == 'bar'.
  scope.$eval(attr.myDirective) == // whatever the value of 'bar' is in the current scope
}

所以你不需要隔离范围。只需用于scope.$eval评估传递给您的指令的表达式。

这是一个快速的小提琴

于 2013-02-15T18:08:52.597 回答