LuckyLuke
LuckyLuke

Reputation: 49057

Directive code executes before controller code

I have created a directive like that I use like this:

<div car-form car="car" on-submit="createCar(car)"></div>

I use directive on both new and edit page that I have created. They have their own controller. In the EditCarController I retrieve the car from a RESTful webservice that I created. I also have assigned a controller function to the directive (in the config object of the directive) where I set some categories based on the car etc...However!

Since the car is loaded asynchrounsly from the page controller it isn't always (random) loaded when the directive controller code starts to run. How can I fix that? I need to be sure that the car I pass to the directive is loaded.

Upvotes: 1

Views: 56

Answers (1)

dnc253
dnc253

Reputation: 40327

You can use a $watch in your directive's controller to know when the data has come back from the server. Something like this:

$scope.$watch("car", function(newVal) {
    if (angular.isDefined(newVal)
    {
         //get stuff based on car (newVal)
    }
});

The $watch will pass in undefined until the data has come back from the server, at which point you can do whatever you need to with the object

Upvotes: 1

Related Questions