Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS using $apply without $scope

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?

like image 578
Mateo Velenik Avatar asked Dec 19 '14 14:12

Mateo Velenik


People also ask

How use $apply in AngularJS?

In AngularJS, $apply() function is used to evaluate expressions outside of the AngularJS context (browser DOM Events, XHR). Moreover, $apply has $digest under its hood, which is ultimately called whenever $apply() is called to update the data bindings.

How do I use $Watch in AngularJS?

The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.

What is the difference between rootScope and scope?

The main difference is the availability of the property assigned with the object. A property assigned with $scope cannot be used outside the controller in which it is defined whereas a property assigned with $rootScope can be used anywhere.

What is the difference between Digest () and apply () Why would you ever call Digest () on a scope?

$digest() gets called without any arguments. $apply() takes a function that it will execute before doing any updates. The other difference is what they affect. $digest() will update the current scope and any child scopes.


1 Answers

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;
    });
  });
});
like image 59
Brocco Avatar answered Sep 24 '22 13:09

Brocco