ui-router inside custom angular directive, make se

2019-05-30 15:47发布

I'm working on an isolated scope custom directive that has a few different states. Does it make sense to use ui-router/ui-view inside this directive in order to handle the states?

It's a "note widget" that lists notes. If there are no notes, it displays a message instead of the list that says they should add a note. If notes are being loaded, it shows that notes are being loaded. If a user adds a note by clicking the add I mentioned above or the + then the view is a textbox. So there is at least 4 different views.

My initial instinct is that it would be polluting the directive and giving it a hard dependency to ui-router and my application because it defines the states. Am I just over worried?

1条回答
你好瞎i
2楼-- · 2019-05-30 16:51

I would tell it this way: yes, use the ui-router, but not for a directive - use it for your appliation. In fact, the best you can do is to read few blog posts and go through sample application to understand the principles. You'll soon realize, that there is no need to use the ui-router partially..

from The basics of using ui-router with AngularJS (by Joel Hooks)

...ui-router fully embraces the state-machine nature of a routing system. It allows you to define states, and transition your application to those states. The real win is that it allows you to decouple nested states, and do some very complicated layouts in an elegant way.

You need to think about your routing a bit differently, but once you get your head around the state-based approach, I think you will like it...

and here AngularJS State Management with ui-router (by Ben Schwartz)

...The most interesting thing about AngularJS's new router, isn't the router itself, but the state manager that comes with it. Instead of targeting a controller/view to render for a given url, you target a state. States are managed in a heirarchy providing inheritance of parent states and complex composition of page components, all the while remaining declarative in nature...

Here I put together all the links, up to date, targeting the sample example, the most interesting code snippet sample.js..

Summary, try to implement the ui-router on the application level. Directive could then by a conductor only, helping your users to navigate, to walk through among states...

查看更多
登录 后发表回答