Reputation:
In my directive I create an isolate scope and assign to the ngModel
in code. Here's my isolate scope:
scope: {
ngModel: '=',
value: "=",
placeholder: "@"
}
Inside the link
function I assign to scope.ngModel
. That works fine if the ng-model
attribute is set on the element, but when it's not it raises an error.
Error: Non-assignable model expression: undefined
What's the preferred way to check if the attribute exists? Do I have to do this explicitly with element.hasAttribute
or am I doing it completely wrong?
Upvotes: 2
Views: 2027
Reputation: 18081
If the ngModel-attribute is optional in your directive you have to check if it exist before you assign any value to the scope variable, or Angular will raise an error. I'd use if( attrs.ngModel ){...}
or element.attrs('ngModel')
to check if it's present.
With ngModel
you also have the option of using the ngModelController in your directive link function. You do this by require:'^ngModel'
(^
if it's optional) and the ngModelController will be available as the fourth argument in your link controller (link:function(scope,element,attrs,ngModelController){ ... }
).
Upvotes: 1