angular input formatter/parser directive and interpolated attributes?

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

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.

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:

passing literal arguments:

<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"; } 

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: '@' } 

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?

directive:

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

回答1:

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.

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' /> 

And in your linking function:

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

So you don't need the isolate scope. Just use scope.$eval to evaluate the expression passed to your directive.

Here's a quick fiddle.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!