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?
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.
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.
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.
$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.
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;
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With