AngularJS - 异步响应更新范围值 [英] AngularJS - updating scope value with asynchronous response
问题描述
我想分享AngularJS控制器之间的一些数据。此外,我打通http请求数据。当我从控制器访问数据,它为空或更高版本(如果通过用户界面手动刷新),数据是可用的。我猜这个问题很相似,这里
但无论我试着在我的情况下,没有工作。请参阅小提琴
I am trying to share some data between AngularJS controllers. Also I get the data through http request. When I access the data from controller, it is null and later (if manually refresh through UI), the data is available. I am guessing the issue is very similar to here But whatever I tried in my case didn't work. Please see the fiddle
http://plnkr.co/edit/6SkzXK?p=$p$ PVIEW
因此,在控制器I通过
so, in controller I get the data through
//myService.setName(); //commented as it breaks the code
它通过的getName()
最有可能可以通过解决, $ rootScope。$适用
,如上面的链接,但我不能使它工作。
it most likely could be solved through, $rootScope.$apply
, as in the above link but I couldn't make it work.
推荐答案
的问题是,当你的控制器初始化,您的getName()的结果复制到一个变量 $ scope.name =为myService .getName()
。由于 $ scope.name
持有一个字符串,而不是它不会被当的getName()
更新变化的参考。
The problems is that when your controller is initialized, you copy the result of getName() to a variable $scope.name = myService.getName()
. Since $scope.name
is holding a string and not a reference it will not be updated when getName()
changes.
有3种方法可以解决这个问题。
There are 3 ways to resolve this.
- 请
$ scope.name = myService.getName
并使用它作为一个功能你好{{名()}}
。 - 请
myService.getName()
返回一个对象像{real_name:富}
,并使用name.real_name
...查看 - 绑定
为myService
的范围和直接用的getName
函数$ scope.myService =为myService;
和视图上的myService.getName()
- make
$scope.name = myService.getName
and use it as an functionHello {{name()}}
. - make
myService.getName()
return an object like{ real_name: "foo" }
and usename.real_name
on the view - bind
myService
to the scope and direct use thegetName
function$scope.myService = myService;
and on viewsmyService.getName()
我preFER第一,鉴于更加清晰。当你有更多的数据,二是良好的。第三个是不是在我速递的好方法。
I prefer the first, given is more clear. The second is good when you have more data. The third isn't a good way in my opnion.
这篇关于AngularJS - 异步响应更新范围值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!