AngularJS,是利用服务好这条路? [英] AngularJS, is this way of using service good?

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

问题描述

我这个HTML:

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

和控制器是:

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

这项服务工作得很好,所以这里我就不贴code ...
在这种情况下,结果是世界,你好!
我以这种方式改变了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>

但是,这并不正常工作。

But this does not work.

我改变了控制器:

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

然后将HTML

and then the 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:

你试过的一员 - 是,暴露在一个范围内的全程服务

The one you've tried - that is, expose the whole service on a scope:

$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.

公开方法逐一

Expose methods one by one

有什么获取曝光precise控制:

to have precise control over what gets exposed:

$scope.getUsername = service.getUsername;

和然后在模板:

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

这需要更多的工作方法,暴露但给你什么获取暴露细粒度控制。

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

揭露代理方式方法

Expose proxing methods:

$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天全站免登陆