2016-05-21 154 views
0

嗨,我很努力讓這個日期/日曆JQuery UI在Angularjs(作爲初學者)工作。 UI部件沒有出現,我得到的錯誤信息是:jquery datepicker UI

類型錯誤:elem.datepicker不是一個函數

我有這個鏈接到jQuery的

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/cupertino/jquery-ui.css"> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script> 
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> 

這是我的HTML視圖:

<div ng-controller="DateCtrl"> 
    <h1> Date: {{date | date:"dd/MM/yyyy"}}</h1> 
    <input type="text" ng-model="date" datepicker /> 
</div> 

這是我的控制器和指令:

.controller('DateCtrl', function($scope) { 
    $scope.date = new Date(); 
}) 
.directive('datepicker', function() { 
    return { 
     restrict: 'A', 
     require : 'ngModel', 
     link : function (scope, elem, attrs, ngModelCtrl) { 
      elem.datepicker({ 
       dateFormat:'dd/mm/yy', 
       onSelect: function (date) { 
        ngModelCtrl.$setViewValue(date); 
        scope.$apply(); 
       } 
      }); 
     } 
    } 
}); 
+0

作爲一個建議,而不是一個答案,你有沒有考慮使用AngularUI的日期選擇器(jQueryUI的專爲角)https://github.com/angular-ui/ui -日期 – haxxxton

回答

1

我複製你的代碼和它的工作對我來說有以下幾點:

確保腳本以正確的順序:

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/cupertino/jquery-ui.css"> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script> 
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> 
<script src="lib/angular.min.js"></script> 
<script src="app.js"></script> 

app.js

// Where 'app' is whatever you're using to define ng-app 
// e.g. <body ng-app="app"> 
var app = angular.module('app', []); 

app.controller('DateCtrl', function($scope) { 
    $scope.date = new Date(); 
}); 

app.directive('datepicker', function() { 
    return { 
     restrict: 'A', 
     require : 'ngModel', 
     link : function (scope, elem, attrs, ngModelCtrl) { 
      elem.datepicker({ 
       dateFormat:'dd/mm/yy', 
       onSelect: function (date) { 
        ngModelCtrl.$setViewValue(date); 
        scope.$apply(); 
       } 
      }); 
     } 
    } 
}); 

至於另一建議我會建議在Angular上使用UI Bootstrap可能更容易。

0

在指令所要求的小變化:

.directive("datepicker", function() { 
     return { 
     restrict: "A", 
     require: "ngModel", 
     link: function (scope, elem, attrs, ngModelCtrl) { 
      var updateModel = function (date) { 
      scope.$apply(function() { 
       ngModelCtrl.$setViewValue(date); 
      }); 
      }; 
      var options = { 
      dateFormat: "dd/mm/yy", 
      onSelect: function (date) { 
       updateModel(date); 
      } 
      }; 
      elem.datepicker(options); 
     } 
     } 
    });