Как решить ошибку модуля при вводе даты и времени? - PullRequest
0 голосов
/ 23 января 2020

Здесь я прикрепил свою зависимость выбора даты и времени

angular.module('HrApp', ['angularjs-datetime-picker']).controller('LeaveController', function($scope, $http) {

  $scope.beforeRender = function($view, $dates, $leftDate, $upDate, $rightDate) {
    var index = Math.floor(Math.random() * $dates.length);
    $dates[index].selectable = false;
  }

  $scope.start = {
    value: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), new Date().getHours() + 1, 0)
  };
  $scope.end = {
    value: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), new Date().getHours() + 2, 0)
  };


  // $scope.day=CalculateDays.add($scope.end-$scope.start);

  $scope.success = false;
  $scope.error = false;


  $scope.type = ["Sick Leave", "Annual Leave", "Unpaid Leave", "Maternity", "Bereavement"];

  $scope.fetchData = function() {
    $http.get('Fetch_LeaveApplication_Data.php').then(function(response) {

      $scope.leaveApplicationData = response.data;
    });
  };

  $scope.openModal = function() {
    var modal_popup = angular.element('#crudmodal');
    modal_popup.modal('show');
  };

  $scope.closeModal = function() {
    var modal_popup = angular.element('#crudmodal');
    modal_popup.modal('hide');
  };

  $scope.addData = function() {
    $scope.modalTitle = 'Add Leave Application';
    $scope.submit_button = 'Insert';
    $scope.TypeOfLeave = "";
    $scope.openModal();
  };

  $scope.fetchSingleData = function(id) {
    $http({
      method: "POST",
      url: "LeaveAction.php",
      data: {
        'id': id,
        'action': 'fetch_single_data'
      }
    }).then(function(data) {
      $scope.TypeOfLeave = data.TypeOfLeave;
      $scope.LeaveStart = data.LeaveStart;
      $scope.LeaveEnd = data.LeaveEnd;
      $scope.hidden_id = id;
      $scope.modalTitle = 'Edit Leave Application';
      $scope.submit_button = 'Edit';
      $scope.openModal();
    });
  };

  /*
   $scope.sendEmail=function()
   {
       $http({

           method:"POST",
           URL:"SendEmail.php",
           data:{
               'TypeOfLeave':$scope.TypeOfLeave,
               'LeaveStart':$scope.start,
               'LeaveEnd':$scope.end
           }
       }).success(function(data){
                 if(data.error != '')
                 {
                     $scope.success = false;
                     $scope.error = true;
                     $scope.errorMessage = data.error;
                 }
                 else
                 {
                     $scope.success = true;
                     $scope.error = false;
                     $scope.successMessage = data.message;


                 }
             });
   }

  */


  $scope.submitForm = function() {

    $http({

      method: "POST",
      url: "LeaveAction.php",
      data: {
        'TypeOfLeave': $scope.TypeOfLeave,
        'LeaveStart': $scope.start,
        'LeaveEnd': $scope.end,
        'action': $scope.submit_button,
        'id': $scope.hidden_id
      }
    }).success(function(data) {
      if (data.error != '') {
        $scope.success = false;
        $scope.error = true;
        $scope.errorMessage = data.error;
      } else {
        $scope.success = true;
        $scope.error = false;
        $scope.successMessage = data.message;
        $scope.form_data = {};
        $scope.closeModal();
        $scope.fetchData();


      }
    });
  };

});

Маршрутизация

/* Routing

*/
var app=angular.module('HrApp',['ngRoute','datatables'])
app.config(['$routeProvider',function($routeProvider){
    $routeProvider.when('/leave',{
       templateUrl:'imodules/Leave/view/Leave.php',
       controller:'LeaveController'
    }).when('/profile',{
       templateUrl:'imodules/Profile/view/profile.html',
       controller:'ProfileController'
    }).
      otherwise({
        redirectTo: 'imodules/Leave/view/Leave.php',
    })
}]);

Это мой код просмотра

<!DOCTYPE html>
<html>

<head>
  <title>AL</title>
  <script src="jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
  <script src="jquery.dataTables.min.js"></script>
  <script src="angular-datatables.min.js"></script>
  <script src="bootstrap.min.js"></script>
  <link rel="stylesheet" href="bootstrap.min.css">
  <link rel="stylesheet" href="datatables.bootstrap.css">


  <link rel="stylesheet" href="angularjs-datetime-picker.css" />
  <script src="angularjs-datetime-picker.js"></script>

  <link href="src/datepicker.css" rel="stylesheet">
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
  <script src="src/datepicker.js"></script>

  <!-- Bootstrap library -->
  <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <script src="bootstrap/js/bootstrap.min.js"></script>

  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment-with-locales.js"></script>
  <script src="vendor/angular-moment-picker/angular-moment-picker.min.js"></script>
  <link href="vendor/angular-moment-picker/angular-moment-picker.min.css" rel="stylesheet">

</head>

<body ng-app="HrApp" ng-controller="LeaveController">

  <div class="container" ng-init="fetchData()">
    <br />

    <br />
    <div class="alert alert-success alert-dismissible" ng-show="success">
      <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> {{successMessage}}
    </div>
    <div align="right">
      <button type="button" name="add_button" ng-click="addData()" class="btn btn-success">Add</button>
    </div>
    <br />
    <div class="table-responsive" style="overflow-x: unset;">
      <table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
        <thead>
          <tr>
            <th>Leave Type</th>
            <th>Start Date</th>
            <th>End Date</th>
            <th>Date Submitted</th>
            <th>Approved by Delegated Person</th>
            <th>Approved by HR Person</th>
            <th>Approved by Management</th>
            <th>Validity</th>


            <th>Withdraw</th>

          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="name in leaveApplicationData">
            <td>{{name.TypeOfLeave}}</td>
            <td>{{name.LeaveStart}}</td>
            <td>{{name.LeaveEnd}}</td>
            <td>{{name.CreatedDateTime}}</td>
            <td><button type="button" class="btn btn-danger btn-xs">Not Approve</button></td>
            <td><button type="button" class="btn btn-danger btn-xs">Not Approve</button></td>
            <td><button type="button" class="btn btn-danger btn-xs">Not Approve</button></td>
            <td><button type="button" class="btn btn-success btn-xs">Valid</button></td>
            <td><button type="button" ng-click="deleteData(name.LeaveID)" class="btn btn-danger btn-xs">Withdraw</button></td>

          </tr>
        </tbody>
      </table>
    </div>

  </div>
</body>

</html>

<div class="modal fade" tabindex="-1" role="dialog" id="crudmodal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form method="post" ng-submit="submitForm()">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">{{modalTitle}}</h4>
        </div>
        <div class="modal-body">
          <div class="alert alert-danger alert-dismissible" ng-show="error">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> {{errorMessage}}
          </div>
          <div class="form-group">
            <label>Type Of Leave</label>
            <select ng-model="TypeOfLeave" name="TypeOfLeave" class="form-control">
              <option ng-repeat="x in type">{{x}}</option>
            </select>
          </div>
          <div class="form-group">
            <label>Leave Start Date Time</label>
            <input type="datetime-local" value="" id="dateTimeInput" size="16" class="form-control" ng-model='start'>

          </div>

          <div class="form-group">
            <label>Leave End Date Time</label>

            <input type="datetime-local" value="" id="dateTimeInput" size="16" class="form-control" ng-model='end'>
          </div>

          <div class="form-group">
            <label>Hour</label>
            <input type="text" value="{{ (end - start)/3600000  }}" id="" size="16" class="form-control" readonly>

          </div>

          <div class="form-group">
            <label>Days</label>
            <input type="text" ng-model='day' id="" size="16" class="form-control" readonly>

          </div>

          <div class="form-group">
            <label>Upload files</label>
            <input type="file" />
          </div>

          <div class="form-group">
            <label>Total emergency leave taken</label>
            <input type="text" value="0" id="" size="16" class="form-control" readonly>

          </div>

        </div>
        <div class="modal-footer">
          <input type="hidden" name="hidden_id" value="{{hidden_id}}" />
          <input type="submit" name="submit" id="submit" class="btn btn-info" value="{{submit_button}}" />
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </form>
    </div>
  </div>
</div>

Если я добавил ['angularjs -datetime-picker '] в модуле выходит с ошибкой inject modulerr. Любая идея, как ее решить.

добавить зависимость выбора даты и времени в модуль

Ответы [ 2 ]

0 голосов
/ 24 января 2020

Код определяет модуль дважды:

ОШИБКА

angular.module('HrApp', ['angularjs-datetime-picker'])

var app=angular.module('HrApp',['ngRoute','datatables'])

Определить зависимости только один раз:

ЛУЧШЕ

angular.module('HrApp', ['ngRoute','datatables','angularjs-datetime-picker'])

Убедитесь, что вы определяете каждый модуль с синтаксисом angular.module(name, [requires]) только один раз для всего проекта. Получить его для последующего использования с помощью angular.module(name).

Из документов:

Создание или извлечение

Остерегайтесь того, что при использовании angular.module('myModule', []) будет создан модуль myModule и перезаписывают любой существующий модуль с именем myModule. Используйте angular.module('myModule') для извлечения существующего модуля.

Для получения дополнительной информации см.

0 голосов
/ 23 января 2020

Я обнаружил различное поведение в разных браузерах angularjs -datetime-picker, протестировано на chrome и safari, неожиданное поведение на safari.

Я предлагаю проверить angular версию должна быть 1,3 +

var app = angular.module('myApp', ['angularjs-datetime-picker']);
app.run(function($rootScope) {
  $rootScope.gmtDate = new Date('2015-01-01 00:00:00 -00:00');
});
app.controller("ctrl", function($scope) {
  $scope.model = "1/1/1991";
  $scope.rows = ['Paul', 'John', 'Lucie'];
  $scope.temp = false;

  $scope.addRow = function() {
    $scope.temp = false;
    $scope.addName = "";
  };

  $scope.deleteRow = function(row) {
    $scope.rows.splice($scope.rows.indexOf(row), 1);
  };

  $scope.plural = function(tab) {
    return tab.length > 1 ? 's' : '';
  };

  $scope.addTemp = function() {
    if ($scope.temp) $scope.rows.pop();
    else if ($scope.addName) $scope.temp = true;

    if ($scope.addName) $scope.rows.push($scope.addName);
    else $scope.temp = false;
  };

  $scope.isTemp = function(i) {
    return i == $scope.rows.length - 1 && $scope.temp;
  };
});
body {
  padding: 20px;
}

.search {
  margin-left: 10px;
}
<!DOCTYPE html>

<html ng-app="myApp" ng-init="
  date1='01-01-2015 00:00:00';
  date2='Thu Jan 01 2015 00:00:00 GMT-0500 (EST)';
  date3='2015-01-01T00:00:00-0400';
  date4='2015-01-01';">

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/angularjs-datetime-picker-v2@0.2.2/angularjs-datetime-picker.js"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/angularjs-datetime-picker-v2@0.2.2/angularjs-datetime-picker.css">

  <!--  -->

  <!-- <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> -->
  <meta charset=utf-8 />
  <title>Angular JS Demo</title>
</head>

<body ng-controller="ctrl">

  &lt;input ng-model="date4" datetime-picker date-only /&gt; <br>
  <input ng-model="date1" datetime-picker="" date-only="" size="30" class="ng-pristine ng-valid ng-valid-date ng-touched"> <br> <br> &lt;input ng-model="date2" datetime-picker date-format="yyyy-MM-dd" date-only /&gt; <br>
  <input ng-model="date2" datetime-picker="" date-format="yyyy-MM-dd" size="30" date-only="" class="ng-pristine ng-valid ng-valid-date ng-touched"> <br> <br> <br> &lt;input ng-model="date3" datetime-picker date-format="yyyy-MM-dd HH:mm:ss" close-on-select="false"
  /&gt; <br>
  <input ng-model="date3" datetime-picker="" date-format="yyyy-MM-dd HH:mm:ss" close-on-select="false" size="30" class="ng-pristine ng-valid ng-valid-date ng-touched"> <br> <br> &lt;input ng-model="date4" datetime-picker hour="23" minute='59'/&gt;<br>
  <input ng-model="date4" datetime-picker="" hour="23" minute="59" size="30" class="ng-pristine ng-valid ng-valid-date ng-touched"> <br> <br> gmtDate : "2020-01-01T11:58:00.000Z"<br> &lt;input type="date" ng-model="gmtDate" size="30" /&gt;<br>

  <input datetime-picker ng-model="addName" />


  <h2>{{rows.length}} Friend{{plural(rows)}} <span ng-show="temp">?<small class="muted"><em > (only {{rows.length-1}} actually....)</em></small></span></h2>


  <form class="form-horizontal">
    <span ng-class="{'input-append':addName}">
    <input id="add" type="text" placeholder="Another one ?" ng-model="addName" ng-change="addTemp()"/>
    <input type="submit" class="btn btn-primary" ng-click="addRow()" ng-show="addName" value="+ add"/>
    </span>

    <span class="search input-prepend" ng-class="{'input-append':search}">
      <span class="add-on"><i class="icon-search"></i></span>
    <input type="text" class="span2" placeholder="Search" ng-model="search">
    <button type="submit" class="btn btn-inverse" ng-click="search=''" ng-show="search" value="+ add"><i class="icon-remove icon-white"></i></button>
    </span>
  </form>
  <table class="table table-striped">
    <tr ng-repeat="row in rows | filter : search" ng-class="{'muted':isTemp($index)}">
      <td>{{$index+1}}</td>
      <td>{{row}}</td>
      <td>
        <button class="btn btn-danger btn-mini" ng-click="deleteRow(row)" ng-hide="isTemp($index)"><i class="icon-trash icon-white"></i></button>
      </td>
    </tr>
  </table>

</body>

</html>
...