最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS - updating scope value with asynchronous response - Stack Overflow

programmeradmin5浏览0评论

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

so, in controller I get the data through

//myService.setName(); //mented as it breaks the code

which sets the value in service and access through getName()

it most likely could be solved through, $rootScope.$apply , as in the above link but I couldn't make it work.

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=preview

so, in controller I get the data through

//myService.setName(); //mented as it breaks the code

which sets the value in service and access through getName()

it most likely could be solved through, $rootScope.$apply , as in the above link but I couldn't make it work.

Share Improve this question edited May 23, 2017 at 11:59 CommunityBot 11 silver badge asked Sep 19, 2012 at 20:16 bsrbsr 58.7k88 gold badges217 silver badges321 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 16

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.

There are 3 ways to resolve this.

  1. make $scope.name = myService.getName and use it as an function Hello {{name()}}.
  2. make myService.getName() return an object like { real_name: "foo" } and use name.real_name on the view
  3. bind myService to the scope and direct use the getName function $scope.myService = myService;and on views myService.getName()

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.

There are three things you need to do to get your plunker to work:

  1. Inject the $http service into the new service
  2. Define the getName() function that the view is calling
  3. Pass the $scope in to the setName() function and change the value on the $scope

http://plnkr.co/edit/6SkzXK

发布评论

评论列表(0)

  1. 暂无评论