简体   繁体   English

无法将更新的控制器绑定为变量以在AngularJS中查看

[英]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". 我的服务正确返回了分配给控制器变量“ 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. PS:我尝试使用$ scope,它非常有效。 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. 我无法理解为什么我无法绑定控制器变量”,并且如果可能,建议何时使用$ scope和此变量。

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. 这只是在javascript中理解“ this”的问题。

Within your controller function 'this' refers to the controller itself. 在控制器功能中,“ this”是指控制器本身。 With in your success callback 'this' no longer refers to the controller (I'm guessing the window if you're not in strict mode?). 在成功回调中,“ this”不再指控制器(如果您未处于严格模式,我猜是在窗口吗?)。

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). 通过将“ this”保存到变量(例如“ vm”),每当您引用vm时,您就知道您正在引用控制器,而不是在该上下文中引用的“ this”(可以更改)。

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. 另外,现在我们在1.5中拥有所有这些功能,最好不要再使用$ scope并始终使用'controllerAs'。 I also suggest moving to components instead of using stand-alone controllers. 我还建议转移到组件而不是使用独立控制器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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