【问题标题】:angular input formatter/parser directive and interpolated attributes?角度输入格式化程序/解析器指令和插值属性?
【发布时间】:2013-02-15 16:28:26
【问题描述】:

我正在尝试编写一个应用于输入元素的可配置指令,该指令需要 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

【问题讨论】:

  • 你能发布你的指令的代码吗?我的预感是你可能没有使用require 键,它可以让你访问ngModel 控制器。

标签: javascript angularjs angularjs-directive


【解决方案1】:

当您添加隔离作用域时,您正在创建全新的子作用域,它不会从包含 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.

【讨论】:

    猜你喜欢
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多