Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do $scope.$apply() with the new `controller as` syntax?

In AngularJS they have $scope.$apply() method to update the UI when there's a model change that is not done through normal AngularJS means.

In the more recent tutorials they recommend using the <controller> as <object> style of instantiating the objects and use this as the scope from their example

.controller('TodoListController', function() {
var todoList = this;

However todoList.$apply() does not appear to work. Am I forced to use $scope.$apply() for this?

like image 453
Archimedes Trajano Avatar asked Feb 18 '26 17:02

Archimedes Trajano


1 Answers

Yes you have to use $scope.$apply(), but that's not a bad thing.

I had this same exact dilemma after reading that one should use controllerAs syntax. I even asked this question a few months later In an isolate scope directive is there any difference between defining variables on scope and defining variables on the controller?

The answer, after thinking about this for a while, is that controllerAs syntax doesn't mean an aversion to $scope, but a design pattern to prevent global state from being stored in $scope because that's when you start nesting scopes, which leads to a lot of problems.

$scope isn't an evil thing. It just lets you screw yourself over, but if you need to use it you shouldn't stop yourself from doing so.

like image 86
m0meni Avatar answered Feb 21 '26 07:02

m0meni