2014-06-06 19 views
1
Having trouble in setting up the default value for the drop down when AngularJS/ng-repeat/custom directive + Select2 JS is used. 

1. I avoided using ng-options as the directive priority is 0. 
2. I tried setting the priority for the custom directive 'select2Directive' to a number less than 1000, but still no luck. 

Plunker @http://plnkr.co/edit/Csy5FqDSQbErTm2fNPac。感謝任何幫助。謝謝。AngularJS - Ng-repeat - Select2 JS - 問題設置默認值

+0

好吧,最後我解決了這個問題,使用超時。 $ timeout(function(){scope。$ apply(select2Inst.select2('val',attrs ['directive-name']));},0); – Jay

+1

更新的工作版本: – Jay

回答

2

我注意到你正在使用一個小指令調用select2,但是我發現這個庫名爲angular-select2,它也易於實現。

你可以設置你的NG-模型/ $範圍的默認值,取lookt這個plunker得到的想法

http://plnkr.co/edit/pFkY5f?p=preview

編輯:

我寧願嘗試以其他方式傳遞數據看起來像select2數據和你的ng-repeat不同步

你可以嘗試一種不同的方法,像創建一個指令並從那裏插入數據。

directive('select2Dynamic', function ($timeout) { 
    return { 
     restrict: 'A', 
     priority: 1, 
     scope: { 
      ngModel: "=" 
      }, 
     require: 'ngModel', 
     link: function (scope, element, attr) { 

      var select2Inst = element.select2(); 
        select2Inst.select2({data:scope.$parent.$eval(attr.ngModel)}); 
        select2Inst.select2('val',attr['select2Dynamic']); 
     } 
     } 
    }); 

<select select2-dynamic='2' ng-model='addresses' id="address" name="address" style="width:200px;" > 
</select> 

,如果你要堅持你的方法,你會考慮來設置值和「模型綁定事件」

看看這個plunker

結束反正我仍然站立我的觀點,你應該嘗試angular-select2庫

希望可以幫助

+0

我的要求是不同的。我必須在下拉列表框中顯示選定的值。我真的不想爲第三方庫尋找一個簡單的指令,我們可以用很少的代碼行來構建這個指令。 – Jay

+0

看看我的更新 –

+1

同意你的替代建議@jack。但正如我前面所說,我的要求是不同的,我的指令在我的應用程序中有多個地方實施。我的解決方案可以工作,並且在指令聲明中需要幾行代碼,而無需像您所建議的那樣編輯任何控制器。 – Jay