简体   繁体   中英

AngularJS: pass parameter between controllers

What i am trying to do:

I have a ListView (or rather an accordion) which contains several items (for simplicity lets assume those have a unique id and a name ). For each item i want to include a link to aa detail-view to show and edit the properties (except for the id ) of that item.

Googling for this returns several results like for example: Passing data between controllers in Angular JS?

and from what i understand the suggested solutions include:

ng-init : (see Can you pass parameters to an AngularJS controller on creation? )

I could initialize a parameter for each item in my List using ng-init inside of the ng-repeat . However by now the angular-documentation advise against this:

The only appropriate use of ngInit for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

service :

It is suggested to use services to share global variables between controllers. I am already doing that by using a service to hold my list of items and use calls to the service to add/delete or change the items. I also implemented a getItem(id) method which i would like to call from the controller of my detail-view. But to do that i need to know the id of the item first!

passing values via $routeParams

The Angular Phonecat Tutorial solves a similar problem by passing parameters via the $routeParams . While this would work, this means I have to include the id of my item in the link to the detail-view. A user could easily change the link and end up in a detail view for a completely different item. If possible, i would rather not expose the internal id in the link to my detail-view!


This seems like a quite common requirement. Is there any best-practice that i am missing?

You have two real alternatives (that you have identified):

  • Use a service
  • Pass the information as part of a url

Both are technically correct and viable but my preference from a semantic and state point of view would be to use a url.

Since you are supplying a clickable link it makes sense that you are linking to something that is linkable (ie an item or state that can be identified by a unique url). If you believe an open accordion item to be more an item of state (as opposed to a page) then you could look into ui-router: https://github.com/angular-ui/ui-router

I'm not sure why you are averse to having item IDs in the url. After all anyone that's interested can see any information in the UI with developer tools. If you don't want database schema information in the UI then there are various methods of ID obfuscation to address this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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