Reputation: 275
I tried to understand angularJS, which has a different approach from what I have seen with its dirty check model update.
Basically, I have a directive ng-draggable
which make elements... draggable. I have a model linking with each of this element with attribute x
and y
– the position of the element linked with the model – and I want the directive to update the model.
To do so, I tried to use the $apply
function in my directive and set the model value x and y. Then I also use the $observe
function to update the view: here is my jsfiddle. (Note I use a factory to catch the mouse event)
var mousemove = function(event) {
var y = event.screenY - startY;
var x = event.screenX - startX;
scope.$apply(function(){
attr.$set('ngModel', {'x': x, 'y': y});
});
}
It seems to work fine. However when I check the model value with the save button (it prints the model in the console), the position x and y are not updated.
So my question is how do I make it work? And more generally what is happening here? Any reading suggestion around the MVC pattern in angularJS (I found the Developer guide a bit harsh for a beginner)
Thank you for your help.
Upvotes: 2
Views: 902
Reputation: 26880
The problem on your approach is that you are changing the entire ngModel
reference instead of changing just one of its properties (x
and/or y
). When you do that, you loose the connection to the initial ngModel
(objects inside players
array) and consequently the connection to the 'real' model (object play
).
Try doing it like this:
scope.$apply(function() {
model.$modelValue.x = event.screenX - startX;
model.$modelValue.y = event.screenY - startY;
});
jsFiddle: http://fiddle.jshell.net/y7nVJ/
Upvotes: 2