AngularJS,这种使用服务的方式好吗? [英] AngularJS, is this way of using service good?

查看:18
本文介绍了AngularJS,这种使用服务的方式好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 HTML:

<p>Hello {{name}}</p>

控制器是:

function myCtrl(scope, service) {
    scope.name = service.getUsername(); // service.getUsername() return "World!"
}
myCtrl.$inject = ['$scope', 'originalService'];

服务运行良好,所以我不在这里粘贴代码...在这种情况下,结果是Hello world!"我以这种方式更改了 HTML:

The service works fine, so i don't paste the code here... In this case the result is "Hello world!" I changed the HTML in this way:

<p>Hello {{service.getUsername()}}</p>

但这不起作用.

我改变了控制器:

function myCtrl(scope, service) {
    scope.ser = service;
}
myCtrl.$inject = ['$scope', 'originalService'];

然后是 HTML

<p>Hello {{ser.getUsername();}}</p>

这有效!

所以我的问题是:

这是直接在 HTML 中使用服务功能的唯一方法,还是我遗漏了什么?

推荐答案

AngularJS 模板只能调用作用域内可用的函数.因此,无论您采用何种方法,您都需要将函数置于作用域中.

AngularJS templates can only invoke functions that are available on a scope. So, whatever approach you take you need to have your function on a scope.

如果您希望可以从模板直接调用服务的功能,您有以下几种选择:

If you want your service's functions to be directly invokable from a template you've got several options:

您尝试过的方法 - 即在范围内公开整个服务:

$scope.service = service;

然后在模板中:

<p>Hello {{service.getUsername();}}</p>

这是控制器中的单行,使所有服务方法在范围内可用,从而对模板可用.

This is one-liner in a controller and makes all the service methods available on a scope and thus to templates.

一一公开方法

精确控制暴露的内容:

$scope.getUsername = service.getUsername;

然后在模板中:

<p>Hello {{getUsername();}}</p>

这需要更多的工作来公开方法,但可以让您对公开的内容进行细粒度的控制.

This requires more work exposing methods but gives you fine-grained control over what gets exposed.

公开代理方法:

$scope.getMyUsername = function() {
   //pre/post processing if needed 
   return service.getUsername();
};

您可以使用这些方法中的任何一种,也可以混合和组合它们,但是归根结底,函数必须以作用域结束(直接或通过作用域上公开的另一个对象).

You can use any of those methods or mix and combine them but at the end of the day a function must end up on a scope (either directly or through another object exposed on a scope).

这篇关于AngularJS,这种使用服务的方式好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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