我有角度指令,用2个选择框替换原始元素,并使隔离范围。但是,第一次更改时,选择框不起作用,之后工作正常。
以下是示例代码:
app.directive('dayMonth', function () {
return {
restrict: 'A',
scope: {
ngModel: '='
},
template: '<div>'+
'<select ng-change="changeDate()" ng-model="month" ng-options="item.number as item.name for item in months" ></select>'+
'<select ng-change="changeDate()" ng-model="day" ng-options="item for item in Range(1,months[month].days)" ></select>'+
'</div>',
replace: true,
controller: function ($scope) {
$scope.months = [
{'number':0,'name':'Month','days':28},
{'number':1,'name':'January','days':31},
{'number':2,'name':'February','days':28},
{'number':3,'name':'March','days':31},
{'number':4,'name':'April','days':30},
{'number':5,'name':'May','days':31},
{'number':6,'name':'June','days':30},
{'number':7,'name':'July','days':31},
{'number':8,'name':'August','days':31},
{'number':9,'name':'September','days':30},
{'number':10,'name':'October','days':31},
{'number':11,'name':'November','days':30},
{'number':12,'name':'December','days':31},
];
$scope.ngModel = '0.0.';
$scope.month = 0;
$scope.day = 0;
$scope.$watch('ngModel', function(val) {
if (val) {
var monthDay = val.split('.');
if ( monthDay.length >= 2 ) {
$scope.month = parseInt( monthDay[1] );
$scope.day = parseInt( monthDay[0] );
}
}
});
$scope.changeDate = function () {
$scope.ngModel = $scope.day + '.' + $scope.month + '.';
};
$scope.Range = function(start, end) {
var result = [];
for (var i = start; i <= end; i++) {
result.push(i);
}
return result;
};
}
}
});
此外,这里是示例plunker
答案 0 :(得分:4)
您的代码是正确的。问题出在你正在使用的Angular版本中。
我用http://code.angularjs.org/1.2.0/angular.js
替换了脚本src,它开始按预期工作(即时更新)。
考虑使用最新的1.2或1.3来解决问题。