如何将datepicker中的数据绑定到常规ng模型

时间:2017-01-19 08:51:23

标签: html angularjs jsp datepicker bind

jsp页面:

<label>Script ID:</label> 
        <input name="scriptId" type="text"
            ng-model="selectedScript.scriptId" 
            ng-disabled="true"
            value="{{selectedScript.scriptId}}" 
            /> 


<form>
        <h1>Date Pannel</h1>
        <fieldset>
        Pick a start date:<br>
        <input ng-disabled = "mode =='BROWSE'" type="date" id="datePickerStart" ng-model="parent.startDate" onchange="document.getElementById('datePickerEnd').setAttribute('min', document.getElementById('datePickerStart').value)"><br><br>
        Pick an end date:<br>
        <input ng-disabled = "mode =='BROWSE'" type="date" id="datePickerEnd" ng-model="parent.endDate"  ><br><br>
        <button ng-disabled = "mode =='BROWSE'" ng-click="setDates()" 
        >Set Dates</button>
        </fieldset>
    </form>

controller.js

$scope.parent = {startDate:''};
$scope.parent = {endDate:''};
$scope.selectedScript.startDate = null;
$scope.selectedScript.endDate = null;


$scope.setDates = function setDates() {
            $scope.selectedScript.startDate = $scope.parent.startDate.getTime();
            $scope.selectedScript.endDate = $scope.parent.endDate.getTime();

            myAppFactory.setDates($scope.selectedScript.startDate, $scope.selectedScript.endDate, $scope.selectedScript.src).success(function(data) {
                $scope.selectedScript.src=data;
            });

        }

这就是我需要完成一些事情所需的所有代码......

现在我的jsp页面上有一张表......

<tr
                ng-repeat="s in scripts
                ng-click="selectScript(s, $index)" 
                ng-class="getSelectedClass(s)">
                <td>{{s.scriptId }}</td>
                <td>{{s.fileName }}</td>
</tr>

controller.js

$scope.selectScript = function(script, index) {
            if ($scope.mode != 'BROWSE')
                return;
            $scope.parent.startDate = $scope.selectedScript.startDate;  <-- this part
            $scope.parent.endDate.setTime = $scope.selectedScript.endDate; <--and this

            $scope.selectedScript = script;
            $scope.selectedRow = index;
        };

当我保存脚本时,数据库中的数据有startDate和endDate 有效...

我的问题是,作为模型的selectedScript,在上面的代码中,在startDate和endDate中没有任何值...它是null(但是字段存在,数据库有我需要的数据)

但我需要以某种方式使parent.startDate和endDate绑定到selectedScript的startDate和endDate ...

顺便说一句,我第一次尝试将日期选择器的ng模型设为selectedScript.startDate,但这不起作用...... 后来我发现datepicker有它自己的范围,这导致了我的问题......至少我是这么认为的。

我只希望自己明白...... 你能救我吗?

1 个答案:

答案 0 :(得分:1)

我认为您的问题是因为当您从数据库中检索数据时,它会将其作为字符串传递,这不是日期选择器可以读取的格式。

基本上你需要做的是将它解析为Date属性,为此你可以这样做;

$scope.parent.startDate = new Date($scope.selectedScript.startDate);
$scope.parent.endDate = new Date($scope.selectedScript.endDate);

在相关位置使用此功能作为日期进行解析,或者您可以设置一个监视器,以便在更改值时为您执行此操作;

$scope.$watch('parent.startDate', function(startDate){
$scope.parent.startDate = new Date($scope.parent.startDate);
});

您只能将$ watch用于单个值,或者您可以将整个对象视为父级&#39;。

希望它有所帮助!