2016-09-06 97 views
2

我在我的頁面上使用Jquery Selectric來呈現我的angularJS應用程序中的選擇框,因此我決定創建一個指令來渲染元素,下面是指令以及我如何使用它。AngularJS jquery指令

的指令:

angular.module('shoeRevamp.directives') 
    .directive('selectric', function() { 
    return { 
     restrict: 'A', 
     scope: {countries: '='}, 
     controller: function ($scope, $element, $attrs) { 
     console.log($scope.countries); 
     }, 
     link: function (scope, el, attrs) { 
     if($("select").length) { 
      $(el).selectric(); 
     } 
     } 
    }; 
    }); 

我如何使用它(玉/帕格):

select(selectric ng-model='country' countries='countries' ng-options='country.name for country in countries track by country.symbol') 

的問題

當我加載頁面並重打開選擇框它抱怨錯誤下面沒有顯示鋪設任何國家:

錯誤消息

jquery.selectric.min.js:1 Uncaught TypeError: Cannot read property 'offsetTop' of undefined 

另一個問題

當我添加priority: -1000,它顯示了國家,但它失去其Selectric風格和行爲。

我需要幫助。

+0

這是你的'我怎麼使用它'部分的玉/帕格? –

+1

@HopefulLlama是的,多謝指出 –

+0

嘗試將鏈接函數包裝到$ timeout ddeclaration中。 –

回答

1

因此,從技術上講,您的問題是,當selectric在DOM上初始化時,您的ng-options尚未填充DOM,因此selectric有一個空列表。

要解決這個問題,您需要使用selectric ajax格式加載數據來構建選項,然後將它們注入selectric下拉菜單中。

的Javascript

.directive('selectric', function ($timeout) { 
    return { 
     restrict: 'A', 
     scope: {countries: '='}, 
     link: function (scope, el, attrs) { 
      var myList = ""; 
      //Loop through the list of countries and build the options 
      for(i = 0; i < scope.countries.length; i++) { 
      myList = myList + "<option value='" + scope.countries[i].symbol + "'>" + scope.countries[i].name + "</option>"; 
      } 
      //Start selectric and append option list 
      el.append(myList).selectric(); 
     } 
    }; 
    }) 
; 

HTML

<select ng-model='country' selectric countries='countries'></select> 

夫婦的事情值得一提:

  • 不能使用NG選項本身與selectric,我嘗試了哈克解決方案,以暫停使用selectric,但創建它自己的問題
  • 因爲你不能使用ng選項,這也意味着你不能使用對象作爲選項值,這會對你的開發施加一些限制。
+0

我有這個方法的一些問題,我無法訪問模型unil我更改選定的項目,訪問它沒有changin選擇項目拋出錯誤'angular.js:13920 TypeError:無法讀取未定義的屬性'國家' –

+0

你確定沒有一個Vanilla JS做你想做的事情嗎? JQuery插件和Angular經常拼寫$ timeout() –