我正在使用自定义指令实现颜色选择器,并希望在用户选择所有蓝色时显示错误消息。设置错误不是问题,但是在错误消息和表单'$ error'属性之间建立连接是。我知道错误正在设置,并且表单变得无效,因为我可以禁用该按钮,但我无法显示错误消息。任何建议将不胜感激。
<body ng-app="app">
<div ng-controller="MainController as mainCtrl">
<form name="myForm">
<h1>Colours</h1>
<label>
Foreground
<colour-picker ng-model="mainCtrl.foreground"></colour-picker>
<p ng-show='myForm.$error.mainCtrl.foregroundBadColour'>Too much blue</p>
</label>
<label>
Background
<colour-picker ng-model="mainCtrl.background"></colour-picker>
<p ng-show="myForm.$error.mainCtrl.backgroundBadColour">Too much blue</p>
</label>
<div ng-style="{'background': mainCtrl.background, 'color': mainCtrl.foreground}" class="results">
Results
</div>
<div>
<button ng-disabled="myForm.$invalid" ng-click="mainCtrl.test">Click Me</button>
</div>
</form>
</div>
<script src="angular.js"></script>
<script src="app.js"></script>
</body>
angular.module('app', [])
.controller('MainController', ['$scope',function($scope){
var mainCtrl = this;
mainCtrl.foreground = '#F00';
mainCtrl.background = '#000';
mainCtrl.test = function(){
alert('Testing Testing');
};
console.log(myForm)
}])
.directive('colourPicker',[function(){
return {
restrict: 'E',
require: 'ngModel',
scope: {},
templateUrl: 'template.html',
link: function($scope, $element, $attributes, ngModelController){
console.log($attributes.ngModel);
console.log($scope);
ngModelController.$formatters.push(function(value){
var colours = value.split('');
console.log(colours);
return {
red: colours[1],
green: colours[2],
blue: colours[3]
}
});
ngModelController.$render = function(){
$scope.red = ngModelController.$viewValue.red;
$scope.green = ngModelController.$viewValue.green;
$scope.blue = ngModelController.$viewValue.blue;
};
$scope.$watch('red + green + blue', function(newValue, oldValue){
ngModelController.$setViewValue({
red: $scope.red,
green: $scope.green,
blue: $scope.blue
})
});
ngModelController.$parsers.push(function(value){
var allBlue = (value.red === '0' && value.green === '0' && value.blue === 'F');
console.log($attributes.ngModel + 'BadColour');
ngModelController.$setValidity($attributes.ngModel + 'BadColour', (!allBlue));
console.log(ngModelController);
return value;
});
ngModelController.$parsers.push(function(value){
return '#' + [value.red, value.green, value.blue].join('');
});
}
}
}]);