简体   繁体   中英

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?

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM