Darren Wainwright
Darren Wainwright

Reputation: 30747

AngularJS two way binding between controller and directive not working

Ok, so I have seen a bunch of these questions here, though I must be missing something trivial.

Please have a look at this Plunkr

In it there is a simple controller that sets an image url. There is also a directive that loads in the template from a script tag.

I have set it up so that the directive changes the imageUrl after 2 seconds though I don't see any of the two-way binding occurring. the image should change, as well as the text.

Can anyone please explain what I am missing here?

i also tried the timeout in the controller too.

any help is appreciated.

Upvotes: 0

Views: 102

Answers (1)

Strille
Strille

Reputation: 5781

The reason is that you are using setTimeout to change the model. Angular is not aware of this since it happens "outside" of Angular. Instead, use Angular's $timeout:

http://plnkr.co/edit/9qYpFdnlaOy3QBDDkBUQ?p=preview

There is a way to manually tell Angular that you have made a change to the model by calling scope.$apply() after setting scope.imageUrl in the setTimeout, but it's better to use $timeout since it will happen automatically.

Upvotes: 1

Related Questions