如何使用自定义$ resource工厂方法重构此angular指令?

时间:2015-05-31 05:39:06

标签: angularjs

我有以下$ resource factory:

app.factory "FeatureKey", ($resource) ->

  $resource "/api/v1/feature_keys/:id", { id: "@id" }

在指令中,我这样使用它:

@search = (term) ->
  FeatureKey.query(name: term).$promise.then (keys) =>
    if keys.length > 0
      @keys = keys
    else
      @keys = [{id: 0, name: term}]
    @current.key = @keys[0]

我想将大部分逻辑移到$ resource工厂,以便我的指令方法如下:

@search = (term) ->
  FeatureKey.search(term).$promise.then (keys) =>
    @keys = keys
    @current.key = @keys[0]

1 个答案:

答案 0 :(得分:1)

您只需让工厂使用search方法返回对象,而不是返回资源:

app.factory "FeatureKey", ($resource) ->
  r = $resource "/api/v1/feature_keys/:id", { id: "@id" }

  search: (term) ->
    r.query(name: term).$promise.then (keys) ->
      if keys.length then keys else [{id: 0, name: term}]

然后你可以像这样使用它:

FeatureKey.search(term).then (keys) =>
  @keys = keys
  @current.key = @keys[0]