简体   繁体   English

AngularJS指令更改输入框的颜色

[英]Angularjs directive change color of input box

I am using angularjs and am pretty new, I need a directive that depending upon a condition it will change the background color of the input box that has the directive attribute. 我正在使用angularjs并且是一个非常新的东西,我需要一个指令,该指令根据条件会更改具有指令属性的输入框的背景颜色。 How do I refeence the calling element to change it's background. 我如何重新定义调用元素以更改其背景。

You can do it with ng-style , anyway, if you really need it wrapped in a directive I've made it for you in Plunkr 无论如何,您都可以使用ng-style ,如果您确实需要将其包装在指令中,则可以在Plunkr中为您完成

It'll update as soon as the input changes. 输入更改后,它将立即更新。

What I'm doing there is watching the color changing and set it to an ng-style within the directive and transcluding it. 我在那里所做的是观察颜色的变化并将其设置为指令中的ng-style并将其包含在内。

Here is a working example of how it would look like using the ng-class: View Demo 这是一个使用ng-class的工作示例: 查看演示

<div ng-app>
<form>
    <input type="text" ng-class="{ error: faulty }"  size="30"/>
    <input type="checkbox" ng-model="faulty"/> check me
</form>

.error { 
    background-color:red; 
    border:2px solid blue; 
}

Please find the below plunk for the example. 请找到以下示例。

I created directive inputBox to do this 我创建了指令inputBox来执行此操作

<input-Box is-maximized="isMaximized" />

The directive is 该指令是

<input type="input" ng-class="{mini: (isMaximized == 1), box: (isMaximized == 0)}" />

Used ng-class and changed the color based on the condition. 使用ng-class并根据条件更改颜色。 if isMaximized is set to 1 in the parent controller it will apply mini class and if it is set to 0 it will apply box class. 如果在父控制器中将isMaximized设置为1,则它将应用迷你类;如果将其设置为0,则将应用盒子类。

http://plnkr.co/edit/ELi3XHk5xWaKMP4MCL2F?p=preview http://plnkr.co/edit/ELi3XHk5xWaKMP4MCL2F?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM