I've switched some Angular Js controller code from using the $scope object t "Controller as syntax with this".
However I can't quite get promises to update "this" correctly in my controllers.
For example in this case I'm making an $http call, and though it is getting called successfully, myProperty does not get updated.
<div ng-controller="MyController as controller">
{{controller.myProperty}}
</div>
<script type="text/javascript">
function MyController($http) {
this.myProperty = "First";
this.myMethod = function(){
this.myProperty = "Second";
$http.get("someUrl.html").success(function(){
this.myProperty = "Third";
});
};
this.myMethod();
};
</script>
Expected result -- "Third" , actual result - " Second"
thisanyways. Add a parameter to your controller, called$scope, and set properties on that which you want to use in the HTML - that's what$scopeis for. The problem with your code is thatthischanges per function, and definitely won't be the samethisinside thesuccesscallback and the controller$scopeis specifically for what the OP is trying to achieve - adding properties that the HTML can access. Why should you have to make a local variable,selfin your example, and reference that everywhere? When you can just inject$scopeand use it properly.knockoutand personally enjoy usingthisas well as enjoy the way thecontrollerAssyntax looks in the view. That being said if the difference is purely preference based I feel the answer to this particular question would be to explain what was actually happening.thisvs.$scope: stackoverflow.com/questions/11605917/… . A great example is that when you use directives and pass it one of your controller methods, thethiswon't be what you expect if the directive calls the method. That's just a simple example, and can definitely cause confusion, just like this postvicjugador, but definitely understand what's going on because this will most likely pop up again as you write moreJavaScript.