[英]How can I turn this into an AngularJs Directive?
我有一个用ng-options填充的选择列表。 它还具有一个“默认”选定项,其行为类似于“占位符”,因为列表没有实际的“占位符”属性。
但是,我要实现的是,仅使第一个(占位符值)的字体颜色比选择列表中的所有其余选项更浅,这与文本输入中的占位符属性的较亮字体非常相似。拥有。
我可以使用它,但是没有编写指令。 我想将此代码移植到指令中,以使其更符合“ Angular Way”并在我的网站上更可重用。
任何帮助将非常感激! 参见下面的代码:
HTML:
<select
ng-model="priority"
id="priority" name="priority"
class="span7"
required
ng-options="p.Description for p in priorities"
ng-class="appliedClass()">
<option value="" selected>select priority</option>
</select>
CSS:
.select-placeholder {
color: #999;
}
JS:
/*
Watches the 'priority' select list for changes
*/
$scope.$watch('priority', function(value) {
// value of the <option> element from the select list
var selectedValue = value;
// applies the 'select-placeholder' css class to ng-class
// if the selected item is the default (placeholder) item.
$scope.appliedClass = function() {
if (selectedValue === undefined) {
return 'select-placeholder';
}
};
});
如果用户确实必须输入值,一种选择是根据:invalid
规则添加required
html5属性和样式:
/* style based on invalid */
select:invalid { color: red }
/* so drop-down items don't inherit color */
select:invalid option { color: black; }
HTML:
<select required>
您可以基于value在CSS中进行所有样式设置,但是value属性更改时不会设置value属性:
/* style based on value */
select[value=""] {
color: #aaa;
}
/* so drop-down items don't inherit color */
select option {
color: black;
}
/* if you want the style in the drop-down list too */
select option:nth-child(1) {
color: #aaa;
}
要解决此问题,您可以使用jQuery根据value属性( fiddle )设置value属性:
$('#priority').attr("value", $('#priority').val())
.change(function() { $(this).attr("value", this.value); });
或有角度的指令( 小提琴 ):
app.directive("setValueAttribute", function() {
return {
restrict: "A",
link: function(scope, element, attrs) {
element.attr('value', element.val());
element.on('change', function(e) {
var that = angular.element(this);
that.attr('value', that.val());
});
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.