2014-11-03 61 views
0

我有角度指令,用2個選擇框替換原始元素,並使隔離範圍。然而,選擇框不工作,我第一次改變它,工作正常後。角度選擇框不能在第一次更改

下面是示例代碼:

app.directive('dayMonth', function() { 
return { 
    restrict: 'A', 
    scope: { 
     ngModel: '=' 
    }, 
    template: '<div>'+ 
       '<select ng-change="changeDate()" ng-model="month" ng-options="item.number as item.name for item in months" ></select>'+ 
       '<select ng-change="changeDate()" ng-model="day" ng-options="item for item in Range(1,months[month].days)" ></select>'+ 
       '</div>', 
    replace: true, 
    controller: function ($scope) { 

     $scope.months = [ 
      {'number':0,'name':'Month','days':28}, 
      {'number':1,'name':'January','days':31}, 
      {'number':2,'name':'February','days':28}, 
      {'number':3,'name':'March','days':31}, 
      {'number':4,'name':'April','days':30}, 
      {'number':5,'name':'May','days':31}, 
      {'number':6,'name':'June','days':30}, 
      {'number':7,'name':'July','days':31}, 
      {'number':8,'name':'August','days':31}, 
      {'number':9,'name':'September','days':30}, 
      {'number':10,'name':'October','days':31}, 
      {'number':11,'name':'November','days':30}, 
      {'number':12,'name':'December','days':31}, 
     ]; 

     $scope.ngModel = '0.0.'; 
     $scope.month = 0; 
     $scope.day = 0; 

     $scope.$watch('ngModel', function(val) { 
      if (val) { 
       var monthDay = val.split('.'); 

       if (monthDay.length >= 2) { 
        $scope.month = parseInt(monthDay[1]); 
        $scope.day = parseInt(monthDay[0]); 
       } 
      } 

     }); 

     $scope.changeDate = function() { 
      $scope.ngModel = $scope.day + '.' + $scope.month + '.'; 
     }; 

     $scope.Range = function(start, end) { 
      var result = []; 
      for (var i = start; i <= end; i++) { 
       result.push(i); 
      } 
      return result; 
     }; 

    } 
} 
}); 

而且,這裏的例子plunker

+0

如何反映「不工作」?究竟是什麼問題? – nullpotent 2014-11-03 16:37:25

+0

它不更改型號,返回空選項。你可以在蹲點檢查出來。 – 2014-11-03 16:41:42

回答

4

你的代碼是正確的。問題出在你正在使用的Angular版本上。

我用http://code.angularjs.org/1.2.0/angular.js替換了腳本src,它開始按預期工作(即時更新)。

考慮使用最新的1.2或1.3來解決問題。

+0

更換蹦牀反映比比正確答案:http://plnkr.co/edit/KHA1Ub3M3FniMKXMSXHL?p=preview – MarcoS 2014-11-03 16:48:19

+0

謝謝!確實如此。猜猜我必須切換到1.2.26。 – 2014-11-04 08:00:55

相關問題