I have the following Angular/HTML which uses Bootstrap CSS classes to indicate whether a form is valid or not using Angular validation.
我有以下Angular / HTML,它使用Bootstrap CSS類來指示表單是否有效使用Angular驗證。
<form name="editor" novalidate>
<div class="form-group" ng-class="{'has-error': editor.name.$dirty && (editor.name.$error.invalid || editor.name.$error.required)}">
<input type="text" class="form-control" name="name" maxlength="150" data-ng-model="name" required />
</div>
</form>
With more than one div.form-group
obviously there is a lot of code repetition. What I would like to do is create an Angular attribute directive which will update the class of the div.form-group
element if the input contained within it is invalid.
有多個div.form-group顯然會有很多代碼重復。我想要做的是創建一個Angular屬性指令,如果包含在其中的輸入無效,它將更新div.form-group元素的類。
This is the markup I would like to get to:
這是我想要的標記:
<div class="form-group" data-form-group data-input="editor.name">
...
</div>
I have the following shell of a directive but I don't know how to monitor the editor.name
(or input
attribute) in order to update the class.
我有一個指令的shell,但我不知道如何監視editor.name(或輸入屬性)以更新類。
myApp.directive("formGroup", function () {
return {
restrict: "A",
scope: {
input: "@"
},
replace: false,
link: function (scope, elem, attrs) {
}
};
});
I assume I need to put the relevant code in the link function, and perhaps using $watch
but other than that I am a bit in the dark
我假設我需要將相關代碼放在鏈接函數中,並且可能使用$ watch但除此之外我有點在黑暗中
1
you should use ngModelController properties for doing this:
你應該使用ngModelController屬性來做到這一點:
myApp.directive("formGroupElement", function () {
return {
restrict: "A",
require: "ngModel"
scope: {
input: "@"
},
replace: false,
link: function (scope, elem, attrs, ngModelController) {
//ngModelController.$setValidity();
}
};
});
or ngFormController:
myApp.directive("formGroup", function () {
return {
restrict: "A",
require: "ngForm"
scope: {
input: "@"
},
replace: false,
link: function (scope, elem, attrs, ngFormController) {
//ngFormController.$setValidity();
}
};
});
1
I have ended up with the following:
我最終得到了以下內容:
myApp.directive("formGroup", function ($parse) {
return {
restrict: "A",
scope: {
input: "@"
},
replace: false,
require: "^form",
link: function (scope, elem, attrs, ctrl) {
var expression = [ctrl.$name, scope.input, "$invalid"].join(".");
scope.$parent.$watch(expression, function (val) {
alert(expression + " " + val); // Pops the value.
});
}
};
});
Note that although the expression in the HTML is editor.name.$error.invalid
, in the link function it is editor.name.$invalid
.
請注意,雖然HTML中的表達式是editor.name。$ error.invalid,但在鏈接函數中它是editor.name。$ invalid。
Using the form controller means I don't have to set the ng-model attribute on the <div>
.
使用表單控制器意味着我不必在
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/02/02/725a1295f074bf36869b5c96bc14a48e.html。