2017-01-03 45 views

回答

0

我已經按照@Floc的答案,並設法讓一個自定義的可重複使用的directive.If有人堅持同樣的問題,那麼可以參考此代碼。

指令

app.directive('tagInput',function($http){ 
    return{ 
    restrict : 'E', 
    templateUrl : 'tag-input.html', 
    scope:{ 
    placeholder : '@', 
    ngModel : '='  
    }, 
    link:function(scope,elem,attrs){ 
    scope.addresses = []; 
    scope.refreshAddresses = function(address){ 
    var params = {address:address,sensor:false}; 
    return $http.get(attrs.url,{params:params}) 
     .then(function(response){ 
     scope.addresses = response.data.results[0].address_components; 
     }) 
    } 
    } 
    } 
    }) 

模板

<ui-select style="width:50%" ng-model="$parent.ngModel" theme="select2"> 
<ui-select-match placeholder="{{placeholder}}">{{$select.selected.long_name}}</ui-select-match> 
<ui-select-choices repeat="address in addresses track by $index" refresh="refreshAddresses($select.search)" refresh-delay="0" > 
    <span ng-bind-html="address.long_name| highlight: $select.search"></span> 
</ui-select-choices> 

這裏傳遞所需的參數(在我的情況下,URL和佔位符)

<tag-input url="https://maps.googleapis.com/maps/api/geocode/json" placeholder="hello"></tag-input> 
0

1)你不必編寫不同的控制器。如果所有的differents API都返回相同的對象結構,那麼您只需將綁定屬性添加到提供API url的自定義指令中即可。然後,您的自定義指令的控制器將能夠使用它。

2)否則,您必須創建返回數據和一個控制器,可以處理不同的API對象或接口。

3)或者,您也可以使用綁定屬性創建自定義指令,該屬性是對象的工廠。然後,當你想使用它的時候,你必須把工廠方法給你的指令。

如果你不知道的綁定屬性做,check this