角度输入格式化程序/解析器指令和插值属性?

时间:2013-02-15 16:28:27

标签: javascript angularjs angularjs-directive

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

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

传递文字参数:

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

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

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

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

如果我在指令定义中读取link函数的attributes参数,我可以在第一次使用中获取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

1 个答案:

答案 0 :(得分: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来评估传递给指令的表达式。

Here's a quick fiddle

相关问题