2013-11-27 76 views
0

我是新來的angularjs和工作指令下拉,但有問題選擇初始值。我必須通過選項的Id來選擇作爲指令的屬性。我將屬性值設置爲一個範圍變量,然後在ng-Init中使用。使用angularjs中的指令在下拉菜單中選擇一個選項

這裏是我的指令代碼:

export class ChoiceGroup 
    { 
     constructor() 
     { 
      var directive: ng.IDirective = {}; 
      directive.restrict = "E"; 
      directive.replace = true; 
      directive.template = '<div><select name="cmbCG" ng-model="dataSel" ng-options="c.DisplayName for c in data"></select></div>'; 
      directive.link = function ($scope: any, element: JQuery, attributes: any) { 
       var injector = angular.element(document).injector(); 
       var key = attributes.key; 

       var cgCacheService: ChoiceGroupsCacheService; 
       seCGCacheService = injector.get('seChoiceGroupsCacheService'); 

       var values: Array<ChoiceValue>; 
       values = seCGCacheService.GetChoiceValues(key); 

       $scope.data = values; 
       if (attributes.selectedvalue) { 
        $scope.selectedvalue = values[attributes.selectedvalue]; 
       } 
      } 

      return directive; 
     } 

的代碼是打字稿。這裏是HTML:

<choicegroupcombo key="RecurrenceFrequency" selectedvalue="3"></choicegroupcombo> 

如果我硬編碼dataSel的價值即NG-的init =「dataSel = 3」,那麼它工作正常,但是當我設置爲範圍變量,然後它不工作。那麼我該如何解決這個問題。

編輯 已解決。我相應地更新了代碼。

+0

這裏有什麼實際的目標是什麼?你的代碼似乎沒有嘗試做任何事情,除了正常的選擇框。 – codevinsky

回答

0

我認爲這可能是一個「過度工程」的經典案例。

您的代碼似乎沒有試圖做任何事情,除了標準選擇框。

試試這個:

app = angular.module('app', []) 

app.controller 'MainCtrl', ($scope) -> 
    # $scope.values = ChoiceGroupsCacheService(key) 
    $scope.values = [ 
    { id: 0, label: 'Zero' } 
    { id: 1, label: 'One' } 
    { id: 2, label: 'Two' } 
    { id: 3, label: 'Three' } 
    ] 
    $scope.number = 2 

和視圖:

<select ng-model="number" ng-options="item.id as item.label for item in values"></select> 

代碼在CoffeeScript中:

這裏有一個plunkr:http://plnkr.co/edit/C6qmUoJ6HjsAT69oavRg

+1

我需要一個指令,因爲我想在應用程序的許多地方重新使用這個下拉菜單 – Haris

相關問題