如何在我的自定义指令中将我的字段设置为 $dirty?
How can I set my field to $dirty inside my custom directive?
我有一个 dropdown/select 指令,用于替换表单中的 select 框。只要表单是原始的,我就设置为禁用几个按钮。
app.directive('dropdown', function ($timeout) {
return {
restrict: 'E',
template: '<div class="btn-group" dropdown>' +
'<button id="dropdownDirective" class="btn dropdown-toggle" dropdown-toggle>' +
'{{ items[ngModel].name }}' +
'<span class="caret"></span>' +
'</button>' +
'<ul class="dropdown-menu" role ="menu" aria-label="dLabel">' +
'<li ng-repeat="item in items">'+
'<a href="#" ng-bind="item.name" ng-click = "select(item)" >< / a >' +
'</li>'+
'</ul>'+
'</div>',
scope: {
ngModel: '=', // selected option
items: '=', // options
},
link: function (scope, element, attrs) {
scope.select = function (item) {
scope.ngModel = item.id;
};
}
};
});
在HTML中:
<dropdown id="modalSelect"
ng-model="ahs.modal.modalId"
items="es.modal.data">
</dropdown>
使用我的指令,$pristine 没有被触发。有人可以指出我做错了什么吗?
您需要在指令中实现与表单相关的整个行为。内容如下:
https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
app.directive('dropdown', function ($timeout) {
return {
require: "ngModel",
restrict: 'E',
template: [...]
scope: {
items: '=', // options
},
link: function (scope, element, attrs, ngModelController) {
ngModelController.$setViewValue(...);
ngModelController.$setPristine(...);
etc.
}
};
});
我有一个 dropdown/select 指令,用于替换表单中的 select 框。只要表单是原始的,我就设置为禁用几个按钮。
app.directive('dropdown', function ($timeout) {
return {
restrict: 'E',
template: '<div class="btn-group" dropdown>' +
'<button id="dropdownDirective" class="btn dropdown-toggle" dropdown-toggle>' +
'{{ items[ngModel].name }}' +
'<span class="caret"></span>' +
'</button>' +
'<ul class="dropdown-menu" role ="menu" aria-label="dLabel">' +
'<li ng-repeat="item in items">'+
'<a href="#" ng-bind="item.name" ng-click = "select(item)" >< / a >' +
'</li>'+
'</ul>'+
'</div>',
scope: {
ngModel: '=', // selected option
items: '=', // options
},
link: function (scope, element, attrs) {
scope.select = function (item) {
scope.ngModel = item.id;
};
}
};
});
在HTML中:
<dropdown id="modalSelect"
ng-model="ahs.modal.modalId"
items="es.modal.data">
</dropdown>
使用我的指令,$pristine 没有被触发。有人可以指出我做错了什么吗?
您需要在指令中实现与表单相关的整个行为。内容如下:
https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
app.directive('dropdown', function ($timeout) {
return {
require: "ngModel",
restrict: 'E',
template: [...]
scope: {
items: '=', // options
},
link: function (scope, element, attrs, ngModelController) {
ngModelController.$setViewValue(...);
ngModelController.$setPristine(...);
etc.
}
};
});