我怎么能叫从AngularJS模板的服务? [英] How can I call a service from a template in AngularJS?

查看:114
本文介绍了我怎么能叫从AngularJS模板的服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回JSON对象,它使服务,为简单起见让说,它看起来是这样的:

I have a service that returns a json object that it makes, for brevity lets say it looks like this:

.service ('levelService', function () {

    // service to manage levels.
    return  {
        levels : [{name:'Base', href:'base'},{name:'Level 1', href:'level1'},{name:'level2', href:'level2'}]
    };

})

我觉得这是很好,但我现在想用它,在一个模板。目前,我有这样的事情:

I think that is fine, but I want to use it now, in a template. Currently I have something like this:

<ul class="dropdown-menu" ng-init="levels = [{name:'Base', href:'base'},{name:'Level 1', href:'level1'},{name:'level2', href:'level2'}];">
                      <li ng-repeat="level in levels">
      <a ng-href="#/modeling/level/{{level.href}}">{{level.name}}</a></li>
                  </ul>

我怎样才能获得NG-初始化到现在使用这项服务?我觉得像做正确的事情,就是服务添加到控制器,但这是任何控制器之外。我是否需要创建此空间的新控制器,或者我可以直接引用服务?

How can I get the ng-init to now use the service? I feel like the right thing to do, is add the service to the controller, but this is outside of any controller. Do i need to create a new controller for this space, or can i directly reference the service?

推荐答案

是的,这将是创建一个控制器最佳实践。

Yes, it would be best practice to create a controller.

在MVC应用程序架构背后的想法是,你不紧密结合你的对象/类在一起。注射服务为一体的控制器,随后你的控制器中加入级别 $范围意味着你的HTML没有担心它来自何处获取数据。

The idea behind the MVC app architecture is that you don't tightly couple your objects/classes together. Injecting a service into a controller, then subsequently your controller adding levels to $scope means that your HTML doesn't have to worry about where it gets the data from.

此外,使用 NG-INIT 以这种方式可以说是罚款敲了一个非常快速的原型,但这种做法不应在生产code使用(如模型的数据本身是紧耦合到您的视图的HTML)。

Also, using ng-init in that way is arguably fine for knocking up a very quick prototype, but that approach shouldn't be used in production code (as your model's data itself is tightly coupled to your view's HTML).

提示:这可能是一个好主意,用一个控制器为你的下拉菜单中的父容器(即页/部分),然后用一个指令为你的下拉菜单本身。想想一个指令作为视图组件。

Tip: It might be a good idea to use a controller for the parent container of your dropdown-menu (ie. the page/section) and then use a directive for your dropdown-menu itself. Think of a directive as a view component.

在一般情况下,你可能会发现在视频教程 egghead.io 有帮助的。

In general, you might find the video tutorials at egghead.io helpful.

这篇关于我怎么能叫从AngularJS模板的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆