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?
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?
Share Improve this question edited Mar 10, 2016 at 11:00 Mateo Velenik asked Dec 19, 2014 at 14:34 Mateo VelenikMateo Velenik 8141 gold badge10 silver badges22 bronze badges 7-
Why do you think you need
$apply()
? Where does that other data e from? - Yourinput
is also set to thename
property - does your new object contain that property? – tymeJV Commented Dec 19, 2014 at 14:35 - Yes, it contains the name property - this new object is ing from a 3rd party control, and angular can't register the change automatically. Anyway, my question is still how to use the $apply method without the use of $scope? – Mateo Velenik Commented Dec 19, 2014 at 14:40
- I think, you can't use $apply without $scope or $rootScope. – Ved Commented Dec 19, 2014 at 14:45
-
Can you post the code where you do
this.myModel=someOtherObjectFromAForeignSource;
. Because the model should be updated IF you are not using a third party library in your controller (like jQuery). – L105 Commented Dec 19, 2014 at 14:47 - There is apply() method in javascript. consider using that.. – Ved Commented Dec 19, 2014 at 14:48
1 Answer
Reset to default 17You 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;
});
});
});