角度输入格式化程序/解析器指令和内插属性? [英] angular input formatter/parser directive and interpolated attributes?
问题描述
我正在尝试编写一个应用于输入元素的可配置指令,该指令需要 ngModel,并为 ngModel 添加解析器和格式化函数.
I am attempting to write a configurable directive that is applied to an input element, which requires ngModel, and which adds a parser and a formatter function for ngModel.
我遇到的问题是我似乎无法在支持 ngModel 绑定的同时将内插值传递到指令中.例如,我希望能够通过以下两种方式之一使用我的指令:
The problem I'm having is that I can't seem to pass interpolated values into the directive while simultaneously supporting ngModel binding. For instance, I want to be able to use my directive in one of two ways:
传递文字参数:
<input ng-model="foo" my-directive="120" />
或从当前作用域传递内插参数:
or passing interpolated arguments from the current scope:
<input ng-model="foo" my-directive="{{bar}}" />
...
function MyCtrl($scope) {
$scope.bar = "120";
}
如果我在我的指令定义中读取链接函数的属性参数,我可以在第一次使用中获得attributes.myDirective的值,但在第二次使用中myDirective的值是未定义的.
If I read the attributes argument of the link function in my directive definition, I can get the value of attributes.myDirective in the first usage, but in the second usage the value of myDirective is undefined.
现在,如果我向指令定义添加一个独立的作用域:
Now, if I add an isolated scope to the directive definition:
scope: { myDirective: '@' }
然后在上面的场景中定义和插入了scope.myDirective,但现在ngModel被破坏了.我的解析器/格式化程序函数的输入参数未定义.发生了什么,我该如何实现我想要的行为?
Then scope.myDirective is defined and interpolated in the scenarios above, but now ngModel is broken. My parser/formatter functions are passed undefined for their input arguments. What's going on, and how can I implement the behavior I want?
指令:
module.directive('myDirective', function () {
return {
restrict: 'A',
require: 'ngModel',
replace: false,
link: function (scope, elm, attrs, ctrl) { // attrs.myDirective not interpolated
推荐答案
当您添加隔离作用域时,您正在创建全新的子作用域,该子作用域不从具有 ngModel
的价值.这就是您的解析器和格式化程序变得未定义的原因.
When you add the isolate scope, you're creating brand-new child scope that doesn't inherit from the scope with the ngModel
's value in it. That's why your parsers and formatters are getting undefined.
此外,在您的示例中,要获取 bar
的值,您不需要将其放在花括号中:
Also, in your example, to get at the value of bar
, you don't need it in curly braces:
<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
来评估传递给指令的表达式.
So you don't need the isolate scope. Just use scope.$eval
to evaluate the expression passed to your directive.
这篇关于角度输入格式化程序/解析器指令和内插属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!