I have read threads on this issue such as: The view is not updated in AngularJS but I still can’t understand how to apply it on my simple example.
I have this function:
function MyPageView($scope) {
var myModel = new MyModel();
$scope.myModel = myModel;
}
when myModel is updated elsewhere in the code (when user clicks, interacts, send XHR requests) it doesn’t update my view. I understand I need to do something with $apply but I didn’t understand where and how.
Can someone explain to me how do I solve this issue for this simple use-case?
My model looks something like this (if that is necessary for the question) – it has no AngularJS code inside of it:
var MyModel = function() {
var _this = this;
...
_this.load = function(){...};
_this.updateModel = function(){...};
...
return _this;
}
adding a JSfiddle example: http://jsfiddle.net/DAk8r/2/
The crux of your problem is that you’re trying to mix AngularJS with a very traditional, "jQuery-soup style" JavaScript pattern. In Angular, you should always use directives to do DOM manipulation and interaction (including clicks). In this case, your code should look more like the following:
Notice how, instead of setting up a manual
clickhandler with jQuery, we use Angular’s built-inng-clickdirective. This allows us to tie in to the Angular scope lifecycle, and correctly update the view when the user clicks the link.Here’s a quote from the AngularJS FAQ; I’ve bolded a part that might help you break the habit.
Finally, here your example, working using this technique: http://jsfiddle.net/BinaryMuse/xFULR/1/