【发布时间】: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