2

Angular automatically puts form elements on the scope: $scope[formName], for example.

It appears my controller is running before this form has been established on the scope ($scope[formName] is undefined).

Form is not present immediately, yet once you click the button, it is present: http://plnkr.co/edit/q3RJLfWWcZhm9Y6oQjy3?p=preview

Is there an event to listen to, or some way to wait until the form has loaded?

Would

$scope.$watch(formName, ...)

work?

2 Answers 2

3

You can use $timeout to allow the digest cycle to perform and then gain reference to your form on the scope:

$timeout(function(){
  $scope.doIt();
}, 0);

But note that you'll need to inject $timeout into your controller:

controller('ctrl1', function($scope, $timeout){

Update here is a working plnkr

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

5 Comments

Hmm, interesting. Not sure why this is necessary, but I like this better, because I'm not sure if $watch will fire multiple times.
It is generally considered bad form to use a watch in a controller, see this article for an in depth explanation: benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html
I would say using $timeout in a controller falls under the same category :)
@tasseKATT I agree w/ you, but as the OP commented above, it is a one-time smell, not multiple. Also, with the exception of form validation checks, I can't come up w/ a scenario when you would want to access the form directly from the controller.
Same here. I don't disagree with your answer :)
2

Yes, it seems $scope.$watch will work:

http://plnkr.co/edit/E9170S4k2GIGz6AKAd8n?p=preview

Not sure if this is the "Angular Way". Any other suggestions?

1 Comment

I recommend doing a watch and deregistering when the form is initialized, that way your function will run only once. It's either that or a timeout, and in that case I personally prefer a watch. Using a timeout can work too, but in other cases it might not work, for example if a variable is initialized on your scope when a REST call is completed..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.