AngularJS。传递服务作为参数传递给指令 [英] AngularJS. Passing Service as an argument to Directive

查看:136
本文介绍了AngularJS。传递服务作为参数传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我自己的指令:<外形包装>

有关现在这个指令使用使用一些服务用户服务),其自身的内部控制

For now this directive uses its own internal controller that use some Service (User service)

这样的:

 directives.directive("formWrapper", ['User',  function(User) {
        return {
         ...        
         controller: function($scope, $location, User) {

                    $scope.fields = User.get( {id: "1"}  );              // GET
        ...

正如你可以看到:我使用硬codeD 服务(用户

问:我怎么能传递服务作为参数传递给指令?要使用这样的:

Question: How could I pass Service as an argument to the Directive? To use it like this:

  Service = comesFromArgument
  $scope.fields = Service.get( {id: "1"} )

我想如果我通过服务名称的字符串(如服务名称),它不会帮助。并通过参数通常发生在链接功能而不是在控制器中。

UPDATE(说明)

在使用 directives.directive(formWrapper,['用户',功能(用户){名用户率先截获用户的服务,这是因为它怎样的方式IoC的工作在这里我想它知道,这是一个服务,但如果我这样做:

When use directives.directive("formWrapper", ['User', function(User) { the name 'User' lead to inject User service, because this it the way how IoC work here I guess. It knows that this is a service. But if I did:

<外形包装服务=用户方式> //这是我想要的

那么,用户将只是一个字符串,而不是引用到用户服务。

Then, "User" will be just a string, not reference to the User service.

推荐答案

您可以使用角的 $注射器服务注入在控制器给出一个字符串的服务。

You can use angular's $injector service to inject a service given a string in your controller.

在HTML:

<form-wrapper my-attr-with-service="User">
  ...
</form-wrapper>

在该指令定义:

controller: function ($scope, $element, $attrs, $injector) {
    var myService = $injector.get($attrs.myAttrWithService);
    // ...
}

这篇关于AngularJS。传递服务作为参数传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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