Michael Lewis
Michael Lewis

Reputation: 4302

AngularJS - controller executes before controller has been loaded

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?

Upvotes: 2

Views: 64

Answers (2)

Brocco
Brocco

Reputation: 64853

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

Upvotes: 3

Michael Lewis
Michael Lewis

Reputation: 4302

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?

Upvotes: 2

Related Questions