2015-05-31 69 views
0

我有以下的$資源工廠:

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] 

我想什麼是最邏輯的移動到$資源工廠讓我的指令方法看起來像這樣:

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

好吧,只是改變了所需的重構。那樣呢? – Nathan

回答

1

你只需要讓你的工廠返回一個對象與search方法,而不是RETURNI納克資源:

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] 
+0

完美!正是我需要的,謝謝。 – Nathan