How to avoid a large number of dependencies in Angularjs

后端 未结 4 2024
旧时难觅i
旧时难觅i 2021-02-05 08:46

I have an Angular application. Its working good, but as my application is getting bigger I\'m worried about the large number of dependencies that I have to inject in each contro

4条回答
  •  暖寄归人
    2021-02-05 09:15

    It's hard to be specific without an exact use case, or seeing the exact code in your controller, but it looks like your controller might be doing too much (or might end up doing too much as you add things later). 3 things you can do:

    • Delegate more of the logic to service(s) that are injected in.

    • Separate out into different controllers, so each only has (just about) 1 responsibility.

    • Separate out into directives, each with their own controllers and templates, and allow options to be passed in, and output given out, via attributes and the scope option of the directive. This is often my preferred option, as you end up building a suite of reusable components, each with a mini-API.

      It is fine for directives to be used like this, at least in my opinion. They aren't just for handling raw Javascript events, or accessing the DOM directly.

提交回复
热议问题