Best way to pass data between ngRoute controllers (from one view to the next)

喜欢而已 提交于 2019-12-23 20:38:15

问题


I'm wondering what's the best (per Angular way) of passing data between views that display on particular route and I would like to avoid passing data via URL as there can be a lot of it or would require some sort of conversion to strings etc. All in all not a good idea.

An example to understand this:

I have a create new content view which displays with empty fields and users are free to enter all the data they want. But in some cases I would like some of these fields to be pre-populated with data based on what users did on previous view.

Each view has its own controller. Would communicating via services maybe still work? Is there any other way and simpler so we don't have to take care of data lifetime (i.e. if we talk via service we have to manually discard data after being read).

I'm wondering what's the Angular-suggested way of doing this?


回答1:


Yep, service or factory would be fine for this case. You could also store that previously entered data in local storage for example using that service. Basically it's better way for improvements in future.

As a simpler way, you can simply use $rootScope. It's available in all your controllers it you wish so.

Just need to inject it into controller or in the app itself.

app.controller('myCtrl', function($rootScope){
    $rootScope.myStoredValues = {...};
});

or

app.run(function($rootScope){
    $rootScope.root = $rootScope; 
    $rootScope.myStoredValues = {...};
    // this way you don't need to inject it into controller, 
    // it will be available there via $scope.root.myStoredValues
});


来源:https://stackoverflow.com/questions/25486392/best-way-to-pass-data-between-ngroute-controllers-from-one-view-to-the-next

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!