How to manually update AngularJS view using ControllerAs syntax?

I am developing a panel with sortable, dockable, floating widgets. One of the controls I use generates floating widgets as HTML at the bottom of the DOM, before the closing body tag. This effectively removes the actions performed in the window controls from the control area in which they are created.

I am developing this control panel controller using controllerAs syntax, but I can’t understand how to efficiently update a view using this syntax when an external component performs an action that affects the data for the view?

Note. This is not the only thing I came across, which forces me to manually update the main view. There are also directives elsewhere on the page that perform actions that affect the presentation.

Ideally, I will never have to update the view manually, because I will use all the commands that occur inside the Angular built-in commands that affect the digest cycle, but that was not an option for me.

So ... if I were using $scope , I could just do:

 $scope.$digest 

Or

 $scope.$apply 

But how can I achieve the same effect using a controller like?

 var vm = this; vm.array = [item, item]; vm.something = something; //External something changes something on a vm.variable vm.update! //How?? 
+5
source share
2 answers

Using the "how" parameter, you determine how you will refer to the area of ​​your controller that you are viewing.

So this is:

 <body ng-controller="MainCtrl"> <p>Hello {{name}}!</p> </body> app.controller('MainCtrl', function($scope) { $scope.name = 'World'; }); 

It is equal to:

 <body ng-controller="MainCtrl as main"> <p>Hello {{main.name}}!</p> </body> 

Your controller:

 app.controller('MainCtrl', function($scope) { this.name = 'World'; }); 

Demo

So basically you should be able to call this.$digest or this.$apply , as you would on $scope .

UPDATE

After doing the search, I think the correct solution should use $scope.apply() or $scope.digest() .

Main resource:
AngularJSs As controller and vm variable
There is a comment raising your question and repeating the author:

You can use $ scope. $ apply () in this case and just enter $ scope for this purpose (still using vm for everything else). However, if you switch using ajax to using Angular $ http, then you do not need call $ apply, since Angular $ http does this for you. This is what I recommend.

Other resources I found:

+6
source

Try making your update in $ scope. $ apply the block as follows:

 $scope.apply(function() { vm.something = some_new_value; }); 

To avoid the "Digest Already Running" error, wrap this in $timeout

0
source

Source: https://habr.com/ru/post/1208177/


All Articles