javascript AngularJS:全局菜单提供者、服务或 rootScope 的正确位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16892162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:23:38  来源:igfitidea点击:

AngularJS: Correct place for global menu provider, service or rootScope?

javascriptangularjsangularjs-scopejavascriptmvc

提问by migajek

I'm new to AngularJS, and - since it is quite complex and the approach is new for me, I'm a bit confused.

我是 AngularJS 的新手,而且 - 因为它非常复杂而且方法对我来说是新的,所以我有点困惑。

I'm from "classic" background (server-side template languages [like Yii, django, Smarty] + some jQuery to make things a bit dynamic).

我来自“经典”背景(服务器端模板语言 [如 Yii、django、Smarty] + 一些 jQuery 使事情变得有点动态)。

Let's say I have a menu bar (Bootstrap NavBar, or anything else) - an element which lives outsideof the main page content, like this:

假设我有一个菜单栏(Bootstrap NavBar 或其他任何东西)——一个位于主页内容之外的元素,如下所示:

<body>
  <div id="menubar">
    ... <!-- menu content -->
  </div>
  <div class="container">
    <div ng-view></div>
  </div>
</body>

Now I'd like to make the menu a bit dynamic, i.e add or remove some menu items inside of the controller. Using the server side frameworks & their templating systems, for example Yii - I'd simply have a BaseControllerclass with $menuItemsvariable, and render it each time in the menuBar, while all the controllers would inherit from BaseControllerso they could modify items.

现在我想让菜单有点动态,即添加或删除控制器内的一些菜单项。使用服务器端框架和他们的模板系统,例如Yii的-我只是有一个BaseController用类$menuItems变量,并在每次渲染它menuBar,而所有的控制器就可以继承BaseController,因此他们可能修改项目。

Also, I need a function which handles the searchFormlocated inside menu bar. Where should it live?

另外,我需要一个处理searchForm位于菜单栏中的函数。它应该住在哪里?

What is Angular way for something like this? So far I've been thinking of creating custom serviceor extending $rootScope.

对于这样的事情,Angular 的方式是什么?到目前为止,我一直在考虑创建自定义service或扩展$rootScope.

回答by vittore

UPDATE: I would encourage you to take a look at John Papa's ng-demoesand style-guideas say second step in adopting angular.js.

更新:我鼓励你看看John Papa 的 ng-demoesstyle-guide作为采用 angular.js 的第二步。

Check out examples angular.js team posted recently, to show full application.

查看 angular.js 团队最近发布的示例,以显示完整的应用程序。

Pay attention to the following features angular gives you

注意angular给你的以下特点

I belive it is going be a good approach to have combination of a service and a directive for rendering menu the way you described it.

我相信将服务和指令结合起来以您描述的方式呈现菜单将是一种很好的方法。