如何从 AngularJS 中的模板调用服务? [英] How can I call a service from a template in AngularJS?

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

问题描述

我有一个服务,它返回一个它制作的 json 对象,为简洁起见,它看起来像这样:

.service('levelService', function () {//用于管理级别的服务.返回  {级别:[{name:'Base', href:'base'},{name:'Level 1', href:'level1'},{name:'level2', href:'level2'}]};})

我认为这很好,但我现在想在模板中使用它.目前我有这样的事情:

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

我怎样才能让 ng-init 现在使用该服务?我觉得正确的做法是将服务添加到控制器,但这是在任何控制器之外.我需要为此空间创建一个新的控制器,还是可以直接引用该服务?

解决方案

是的,最好创建一个控制器.

MVC 应用程序架构背后的理念是,您不会将对象/类紧密耦合在一起.将服务注入控制器,然后您的控制器将 levels 添加到 $scope 意味着您的 HTML 不必担心它从哪里获取数据.>

此外,以这种方式使用 ng-init 可以说很适合构建一个非常快速的原型,但这种方法不应该用于生产代码(因为您的模型数据本身是紧密耦合的)到您视图的 HTML).

提示:最好为 dropdown-menu 的父容器(即页面/部分)使用控制器,然后为 dropdown 使用指令-menu 本身.将指令视为视图组件.

一般来说,您可能会发现 egghead.io 上的视频教程很有帮助.

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>

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.

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.

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.

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

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

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