第一件事,專業的拼寫是錯誤的前三輸入模型。
現在要回答你的問題,你的方法的問題是,你正在使用4個不同的屬性來存儲/引用1值,即日期。就我所知,這不是純粹的角度方式。
您只需要將其存儲在1個屬性中,即professional.start_date,然後將日期月份和年份從相同的位置分開,除非您確實有某些事情要與日期月份和年份分開進行。我希望我很清楚。請閱讀下面。
ngModelController
給我們$formatters
和$parsers
,它格式/解析你的模型/視圖,並將它們呈現給視圖或將它們存儲回相應的模型。你應該使用它們。下面的實施。
的Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body ng-app="myApp" ng-controller="AppController">
<div class="infoDateBox">
<input dd-directive type="text" placeholder="DD" ng-model="professional.start_date">
<input mm-directive type="text" placeholder="MM" ng-model="professional.start_date">
<input yyyy-directive type="text" placeholder="YYYY" ng-model="professional.start_date">
</div>
<span class="seperator">-</span>
<table>
<tr>
<td>Start date</td>
<td><input type="text" ng-model="professional.start_date"></td>
</tr>
</table>
<script src="angular.js" type="text/javascript "></script>
<script src="app.js" type="text/javascript "></script>
</body>
</html>
app.js
var myApp = angular.module('myApp', []);
myApp.controller('AppController', function($scope) {
$scope.professional = {};
$scope.professional.start_date = new Date();
});
myApp.directive('yyyyDirective', function($filter)
{
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelController)
{
ngModelController.$formatters.push(function(data)
{
return $filter('date')(data, "yyyy");
});
ngModelController.$parsers.push(function(data)
{
var d = new Date(ngModelController.$modelValue);
d.setYear(data);
return d;
});
}
};
});
myApp.directive('mmDirective', function($filter)
{
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelController)
{
ngModelController.$formatters.push(function(data)
{
return data.getMonth()+1;
});
ngModelController.$parsers.push(function(data)
{
console.log(data);
var d = new Date(ngModelController.$modelValue);
if(data.length!=0)
{
d.setMonth(parseInt(data)-1);
}
else
{
d.setMonth(0);
}
return d;
});
}
};
});
myApp.directive('ddDirective', function($filter)
{
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelController)
{
ngModelController.$formatters.push(function(data)
{
return $filter('date')(data, "dd");
});
ngModelController.$parsers.push(function(data)
{
var d = new Date(ngModelController.$modelValue);
d.setDate(data);
return d;
});
}
};
});
該代碼可以優化,但我寫它理解目的的方式。如果您有任何疑問,請告訴我。文檔here
我可以看到你的控制器嗎? – Luke101
@ Luke101我已更新它。我需要將月份,日期和年份複製到start_date字段。你有什麼建議嗎? – akbarbin
如果我的回答是正確的,請將其標爲正確) –