繁体   English   中英

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

[英]Unable to bind updated controller as variable to view in AngularJS

视图:

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

控制器:

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.
  });
}]);

我正在尝试使用“控制器为”方法从控制器访问值。 我的服务正确返回了分配给控制器变量“ this.city”的城市名称。 但我无法在“视图”中绑定值”(我看不到视图中显示的任何内容)

如果我做错了,请告诉我。 PS:我尝试使用$ scope,它非常有效。 我无法理解为什么我无法绑定控制器变量”,并且如果可能,建议何时使用$ scope和此变量。

提前致谢 :)

由于原始问题已得到解答,因此我将尽力解释答案。 这只是在javascript中理解“ this”的问题。

在控制器功能中,“ this”是指控制器本身。 在成功回调中,“ this”不再指控制器(如果您未处于严格模式,我猜是在窗口吗?)。

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

另外,现在我们在1.5中拥有所有这些功能,最好不要再使用$ scope并始终使用'controllerAs'。 我还建议转移到组件而不是使用独立控制器。

暂无
暂无

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

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