我们有一个指令(比方说复选按钮)创建一个具有某些特定功能的样式化复选框。
我在指令中需要 ng-form,所以我可以在指令中使用 formCtrl,我成功地将 form 设置为 $dirty 或 $valid。 我的问题 是如何将指令创建的特定元素设置为 $valid 或 $dirty 并且通常表现为 Angular 形式元素。只是做 element.$valid = false
并不像 fromCtrl.addControl(element)
那样工作所以我被卡住了。我应该强调这个指令在 ng-repeat 循环中使用,所以我可以在它上面设置一个“名称”,因为 ng-repeat 可以编程设置一个名称(必须是一个字符串)
这是(简化的)模板:
<div class="check-button ">
<div c" ng-class="{ 'active': value != undefined ? btnState == value : btnState }">
<i class="icon-ok"></i>
</div>
<div class="pull-left btn-label" ng-transclude></div>
</div>
这是代码:
angular.module('our.directives').directive('checkButton', [function() {
return {
restrict: 'A',
require:'?^form', //may be used outside a form
templateUrl: '/tempalte/path/tpocheckbutton.html',
scope: {
btnState: '=ngModel',
value: '=radioBtn'
},
replace: true,
transclude: true,
link: function($scope, $element, $attrs, formCtrl) {
if(formCtrl){
formCtrl.$addControl($element)//doesn't work
}
$scope.$watch(function() {
return $scope.btnState;
}, function(newValue) {
$scope.btnState = newValue;
});
var _onElementClick = function() {
if($scope.value != undefined) {
$scope.btnState = $scope.value;
} else {
$scope.btnState = !$scope.btnState;
}
if(formCtrl){
// $element.$dirty = true;//doesn't work
formCtrl.$setDirty(); //does set the form as dirty - but not the field
}
};
$element.find('.button, .btn-label').on('click', _onElementClick);
}
};
}]);
我们使用的是最新的 Angular 版本 (1.2.10)
最佳答案
您基本上需要 form
和 ngModel
作为 form.$addControl
需要一个 ngModelController
。
关于angularjs - Angular 形式 : setting a $dirty property on a custom directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21444013/