2013-10-21 55 views
1

我想在AngularJS中使用jquery timepicker插件創建一個timepicker指令。 (我無法獲得任何現有的角度計時器在IE8中工作)。如何在AngularJS中正確設置我的timepicker指令的值?

到目前爲止,我已經能夠獲得指令,以便在選擇時間時更新範圍。但是,我現在需要完成的是獲取輸入來顯示時間,而不是頁面第一次加載時模型值的文本。請看下圖:

這是表明:enter image description here 這就是我想要的:enter image description here

這裏是我的指令:

'use strict'; 

    playgroundApp.directive('timePicker', function() { 
     return { 
      restrict: 'A', 
      require: "?ngModel", 
      link: function(scope, element, attrs, controller) { 
       element.timepicker(); 
      //controller.$setViewValue(element.timepicker('setTime', ngModel.$modelValue)); 
      //ngModel.$render = function() { 
      // var date = ngModel.$modelValue ? new Date(ngModel.$modelValue) : null; 
      //}; 

      //if (date) { 
      // controller.$setViewValue(element.timepicker('setTime', date)); 
      //} 

      element.on('change', function() { 
       scope.$apply(function() { 
        controller.$setViewValue(element.timepicker('getTime', new Date())); 
       }); 
      }); 
     }, 
    }; 
}) 

註釋代碼是我一直嘗試,但它不沒有工作。我得到一個讀取錯誤,ngModel未定義。因此,爲了澄清,當頁面第一次加載時,如果該輸入字段有模型,我希望輸入只顯示時間,就像在選擇一個值後顯示的那樣。

謝謝。

編輯:

好,使得一些試驗和錯誤更改後,我的鏈接功能如下:

link: function (scope, element, attrs, controller) { 
     if (!controller) { 
      return; 
     } 

     element.timepicker(); 

     var val = controller.$modelValue; 

     var date = controller.$modelValue ? new Date(controller.$modelValue) : null; 

     controller.$setViewValue(element.timepicker('setTime', controller.$modelValue)); 
     //ngModel.$render = function() { 
     // var date = ngModel.$modelValue ? new Date(ngModel.$modelValue) : null; 
     //}; 

     if (date) { 
      controller.$setViewValue(element.timepicker('setTime', date)); 
     } 

     element.on('change', function() { 
      scope.$apply(function() { 
       controller.$setViewValue(element.timepicker('getTime', new Date())); 
      }); 
     }); 
    }, 

這不會給我任何錯誤,但是$ modelValue始終爲NaN 。這裏是我的控制器代碼:

$scope.startTime = new Date(); 
$scope.endTime = new Date(); 

及相關HTML:

<input id="startTime" ng-model="startTime" time-picker/> 
    <input id="endTime" ng-model="endTime" time-picker /> 

有沒有別的東西,我需要做什麼?

+0

您使用哪個timepicker插件? –

+0

https://github.com/jonthornton/jquery-timepicker#timepicker-plugin-for-jquery –

回答

3

我花了好幾天用相同的插件努力沒有取得成果,最終我找到了另:

http://trentrichardson.com/examples/timepicker/

它完美使用以下指令:

app.directive('timepicker', function() { 
    return { 
     restrict: 'A', 
     require : 'ngModel', 
     link : function (scope, element, attrs, ngModelCtrl) { 
       $(function(){ 
        element.timepicker({ 
        onSelect:function (time) { 
         ngModelCtrl.$setViewValue(time); 
         scope.$apply(); 
        } 
        }); 
       }); 
     } 
    } 
}); 

我希望你能找到有用。

相關問題