Sebastien
Sebastien

Reputation: 6660

Directive scope update does not update controller scope (AngularJs)

I have an issue witn angularjs, I created a factory and a directive on an input. In my directive, when the value of the input change, I want to update the controller value. But in fact, I am one event late in my controller. I explain myself:

I created a plinkr to demonstrate my issue:

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

Thank you

Upvotes: 0

Views: 1200

Answers (1)

Jan
Jan

Reputation: 1000

There are several things wrong here

  1. Do not call your own attribute ng-model. ngModel is already used for attaching a ModelController to a formfield. You cannot simply use the same attribute for a different purpose and be surprise when things conflict :)

  2. The ngModel-Directive already takes care of binding your input fields value to a property on the scope. No need to do that with element.keydown.

  3. Even if what you were doing in element.keydown was valid, you need to wrap the entire callback in scope.$apply() so that the change can be reflected throughout the app. This is the primary cause for the delay you're observing.

Apart from these concrete points, the way you wrote this example indicates a misunderstanding of some basic concepts in AngularJS. Explaining all these from the ground up would exceed the scope of this answer. I recommend reading up on directives and looking how some of AngularJS built-in directives are implemented. You can see their sourcecode here.

Upvotes: 3

Related Questions