2016-09-06 99 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() –