0

When trying to access a form field's $valid property from inside the controller, I get "cannot access $valid of undefined." Here's what I've tried, based on other answers on SO, to no avail:

  1. Use controllerAs - I was already using controllerAs in my route but for good measure I added an ng-controller="TestCtrl as testCtrl" to my container DIV.
  2. Try ng-init, passing the scope - I added an ng-init to the form tag (ng-init=testFunction(this) that calls a controller function to set a property on the scope called formScope (as seen here: AngularJs can't access form object in controller ($scope))
  3. Try scope = {} in your controller
  4. Several other suggestions that I fail to remember right now.

My requirements are, to me, simple: When the field loads (controller loads the model data), we need to:

  1. Show the appropriate validation glyphicon next to the field.
  2. When the field's validity changes, the glyphicon needs to change accordingly
  3. Icons:
    when $valid = false, use glyphicon-remove
    when $valid = true, use glyphicon-ok
    when $valid = null or undefined (possible?), use glyphicon-warning-sign
  4. Be able to pass the validity to a directive (future use)

See the following plunk: https://embed.plnkr.co/XXFM6Mtt1KnSci5yagTd/

Any help or different approaches is appreciated. This is kicking my butt. Thanks

1 Answer 1

2

Replace

self.sexValid = testForm.sex.$valid;

by

self.sexValid = self.testForm.sex.$valid;

That said, why duplicate that information in a field of the controller, instead of simply using

testCtrl.testForm.sex.$valid

directly in the view?

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

1 Comment

Good point. Overthinking the problem I guess. I appreciate the help - I tried it in my real app and it works there too. Thanks so much.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.