如果输入不为空或焦点,我需要将类添加到输入父级,因为我想更改标签位置。
<div class="input-field">
<input type="email" name="email" ng-model="email" required />
<label for="email">Email</label>
</div>
我可以这样做:
<div class="input-field" ng-class="{ active: signIn.email.$viewValue.length > 0 || isFocus }">
<input type="email" name="email" ng-model="email" ng-focus="isFocus=true" ng-blur="isFocus=false" required />
<label for="email">Email</label>
</div>
但是我有很多输入,我的代码会非常庞大和丑陋。
我怎样才能做得更好?
谢谢。
答案 0 :(得分:0)
您可以使用范围变量。
myApp = angular.module("myApp",[]).controller("myController",['$scope',function($scope){
var someCondition = 2 > 1;
$scope.myClass = {
active : someCondition ? "active" : "not-so-active"
}
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<div class="input-field" ng-class="{{myClass}}">
<input type="email" name="email" ng-model="email" ng-focus="focus=true" ng-blur="focus=false" required />
<label for="email">Email</label>
</div>
</div>
&#13;
答案 1 :(得分:0)
使用属性指令,您可以在其中拥有需要添加到输入字段的逻辑类。
angular.directive('myClass', function() {
return {
restrict: 'A',
link: function (scope, element,attr) {
// your logic
}
};
or
$scope.myClass = "";
<div class="input-field" ng-class="myClass" />