简体   繁体   中英

Unable to bind updated controller as variable to view in AngularJS

View:

<div ng-controller="MainPageController as mpc">
    <h1>{{mpc.city}}</h1>
</div>

Controller:

app.controller('MainPageController',['GetCityService', function(GetCityService){
  this.city = null;
  this.getCityService = GetCityService;
  this.getCityService.getCity().success(function(data){
      this.city = data.city
      console.log(this.city); // Prints the city correctly.
  });
}]);

I am trying to use "controller as" method to access values from controller. My service returns the city name correctly which is assigned to controller variable "this.city". but I am unable to bind the value in the View" (I see nothing displayed in the view)

Please let me know if I'm doing it wrong. PS: I tried to use $scope, it perfectly works. I am unable to understand why I am unable to bind the controller variable" and If possible suggest when $scope and this variables should be used.

Thanks in advance :)

Since the original question has been answered, I'll try to explain the answer. It's just a matter of understanding 'this' in javascript.

Within your controller function 'this' refers to the controller itself. With in your success callback 'this' no longer refers to the controller (I'm guessing the window if you're not in strict mode?).

By saving 'this' to a variable, such as 'vm', whenever you refer to vm you know that you are referencing the controller, and not whatever 'this' refers to in that context (which can change).

On another note, now that we have all these features in 1.5, it's best to not use $scope anymore and to use 'controllerAs' all the time. I also suggest moving to components instead of using stand-alone controllers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM