2

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?

1
  • You can't have optional two-way-binding (=). You could however optionally ?^require the model, and have it injected to your link-function as the 4th parameter. Commented May 12, 2013 at 14:23

1 Answer 1

1

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){ ... }).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.