2012-11-04 61 views
5

雙向數據綁定,帶有Ajax功能的AngularJS + Angular-UI Select2。雙向數據綁定,帶有Ajax功能的Angular-UI Select2

我創建了一個指令,以通用方式實現Select2下拉Ajax行爲: - (它需要幾個屬性來獲取formatResult,formatSelection方法調用和url)。

我的問題是如何加載「編輯模式」中的值,從下拉列表中選擇的值是在formatselection方法中收到的,但是在加載屏幕時,我想從它綁定到的相同值加載下拉列表。 實施例: -

<input type="hidden" for="part" class="bigdrop" style="width: 250px" formatresult="partFormatResult" formatselection="partFormatSelection" aurl="/api/Part" search-drop-down ui-select2="configPartSelect2" ng-model="product.SalesPart" data-placeholder="Select Part" ng-change="onPartSelect();" /> 

    Directive Code 

    One23SRCApp.directive('searchDropDown', ['$http', function (http) { 
     return function (scope, elm, attrs) { 
      var raw = elm[0]; 
      var fetchFuncName = "fetch" + attrs["uiSelect2"]; 
      console.log("Directive load pat " + scope[attrs["ngModel"]]); 
      scope[fetchFuncName] = function (queryParams) { 
       var result = http.get(queryParams.url, queryParams.data).success(queryParams.success); 
       result.abort = function() { 
        return null; 
       }; 
       return result; 
      }; 


      scope[attrs["uiSelect2"]] = { 
       minimumInputLength: 3, 
       initSelection: scope[attrs["initselection"]], 
       ajax: { 
        url: attrs["aurl"], 
        data: function (term, page) { 
          return { params: { isStockable: true, query: term, pageNo: page, pageSize: 20 } }; 
        }, 
        dataType: 'json', 
        quietMillis: 100, 
        transport: scope[fetchFuncName], 
        results: function (data, page) { 
         var more = (page * 20) <= data.length; // whether or not there are more results available 
         return { results: data, more: more }; 
        } 
       }, 
       formatResult: scope[attrs["formatresult"]], 
       formatSelection: scope[attrs["formatselection"]], 
       dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller 
      }; 

      return { bind: attrs["ngModel"] }; 
     }; 

    }]); 

//inside controller- 
after loading of data 
    $("#partDD").select2("val", product.SalesPart); 
//$scope.partInitSelection definition. 
    $scope.partInitSelection = function (element, callback) { 
     if (! $scope.PartList) { 
      $scope.PartList = [$scope.product.SalesPart]; 
     } else { 
      $scope.PartList.push($scope.product.SalesPart); 
     } 
     callback($scope.product.SalesPart); 
    }; 

} 
+0

也許你應該設置一個plunker http://plnkr.co/。 – maxisam

+0

設置一個plunkr對我來說很困難,因爲我不知道如何模擬ajax,可能我在這裏提到了我的問題 - https://github.com/ivaynberg/select2/issues/560 –

回答

0

固定它終於: - 正如我在範圍保持配置對象[ATTRS [ 「uiSelect2」]], 我每個I加載時間稱爲上述配置對象的.ajax.data方法數據。

scope[attrs["uiSelect2"]].ajax.results(product.SalesPart.text, 1);