AngularJS using $apply without $scope

All we need is an easy explanation of the problem, so here it is.

I started working with AngularJS and I embraced the convention for writing controllers with this, not with $scope. So my controllers look like this:

myApp.controller("SomeController", function(){
    this.myModel={id:-1, name:"empty"};
});

<div ng-controller="SomeController as ctrl">
    <input type="text" ng-model="ctrl.myModel.name" />
</div>

Now, I changed the myModel object in the controller in a way like this:

this.myModel=someOtherObjectFromAForeignSource;

… and the value inside the input control doesn’t change. I read about the $apply function and it’s use but since i use the “this” convention, I don’t have a $scope variable.

How do I call the $apply method?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can certainly still use $scope with the controller as syntax with no issue.

In fact that is how you would handle events ($on, $broadcast, $emit) just inject it into your controller:

app.controller('MyCtrl', function($scope){
   //set your properties/methods as you are
   this.message = 'foo';
   this.yell = function(){
     this.message = this.message.toUpperCase() + '!!!';
   };

  var vm = this;
  //and use $apply as needed
  somethingOutsideOfAngular(function(value){
    $scope.$apply(function(){
      vm.message = value;
    });
  });
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply