簡體   English   中英

無法使用 Angular.js 獲取輸入字段值

[英]Cannot get the input field value using Angular.js

我無法使用 Angular.js 找到輸入字段值。 我在下面提供我的代碼:

<div class="input-group bmargindiv1 col-md-12">
    <span class="input-group-addon ndrftextwidth text-right" style="width:180px">From Time :</span>
    <input type="text" name="time" id="time" class="form-control oditek-form" placeholder="E.G-9.00AM-10.00AM" ng-model="time" ng-keypress="clearField('time');" maxlength="30">
</div>
<div class="input-group bmargindiv1 col-md-12">
    <span class="input-group-addon ndrftextwidth text-right" style="width:180px">To Time :</span>
    <input type="text" name="time1" id="time1" class="form-control oditek-form" placeholder="E.G-9.00AM-10.00AM" ng-model="time1" ng-keypress="clearField('time1');" maxlength="30">
</div>

這里我集成了jquery-timepicker ,腳本如下。

$(function() {
    $('#time').timepicker();
    $('#time1').timepicker();
});

我的問題是,當我嘗試使用一個ng-click事件獲取這些值時選擇了時間值后,它顯示未定義。

$scope.addTimeDetails = function() {
    console.log('times', $scope.time, $scope.time1);
}

將 AngularJS 與 jQuery 庫混合使用是一個糟糕的解決方案。 接下來的問題是:您在輸入上定義 ng-model,然后初始化 jQuery timepicker,這會產生問題。 您應該為 datepicker 使用一些第三方 angularjs 庫或構建您自己的指令。 這個類似於 jQuery 時間選擇器: angular-jquery-timepicker

這行不通,因為 jquery-datepicker 修改了 DOM。 您可以嘗試使用angular-datepickerangular UI bootstrap

ngModels 應該總是有自己的對象而不是范圍屬性:

<input type="text" ng-model="formModel.time">

在您的控制器中:

$scope.formModel = {};

然后,您將能夠通過以下方式訪問該值:

$scope.formModel.time;

jQuery的timepicker可能不會觸發keypress事件。

ng-change試試

<input type="text" name="time" id="time" class="form-control oditek-form" placeholder="E.G-9.00AM-10.00AM" ng-model="time" ng-change="clearField('time');"  maxlength="30" >

在 angular 中使用第三方庫時,推薦的方法是創建如下指令:

angular.module('app', [ ])
    .directive('timePicker', [function () {
        return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            model: '=ngModel'
        },
        link: function ($scope, element, attrs, ngModelCtrl) {

            element.timepicker();

            element.on('changeTime', function () {
                $scope.$apply(function () {
                    $scope.model = element.val();
                });
            });       
        }
    }
}]);

並使用從作為:

<input type="text" ng-model="time" time-picker="" />
<input type="text" ng-model="time1" time-picker="" />

推薦資源: think-in-angularjs-if-i-have-a-jquery-background

<script>
$(function() {
    $('#time').timepicker({change: function(time) {
        // the input field
        $scope.time = time;
        if (!$scope.$$phase) $scope.$apply();
    }});
    $('#time1').timepicker({change: function(time) {
        // the input field
        $scope.time1 = time;
        if (!$scope.$$phase) $scope.$apply();
    }});
});
<script>   

您需要將此代碼放在 angular js 控制器中以在模型中設置值而不是放入 HTML。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM