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
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.
来源:https://stackoverflow.com/questions/14899017/angular-input-formatter-parser-directive-and-interpolated-attributes