What would be the most efficient way of conditionally changing the background color for a required input once it is valid using AngularJS 1.5.6? Per my understanding and what I have read online, I should avoid using $scope and instead use controllerAs. How would I refactor to the follow AngularJS code to use controllerAs?
HTML
<input id='textfield' placeholder='Search' required>
CSS
#textfield:valid {
background-color: green;
color: white;
}
HTML
<div ng-app="myApp" ng-controller="testController">
<input type="text" ng-class="cssClass" ng-change="changeCssInput()" ng-model="text"/>
</div>
CSS
.input-green {
background-color: green;
color: white;
}
.input-red {
border: 3px solid red;
}
AngularJS
angular.module('myApp', []).
controller('testController', function ($scope)
{
$scope.text = '';
$scope.cssClass = 'input-red';
$scope.changeCssInput = function () {
$scope.cssClass = $scope.text.length <= 0 ? 'input-red' : 'input-green';
}
});
What would be the most efficient way of conditionally changing the background color for a required input once it is valid using AngularJS 1.5.6?
(Below code is written using controllerAs
syntax, see below for more info about controllerAs
syntax)
<input type="text" ng-class="ctrl.text.length <= 0 ? 'input-red' : 'input-green'" ng-model="ctrl.text"/>
How would I refactor to the follow AngularJS code to use controllerAs?
Using controllerAs syntax
HTML
<div ng-app="myApp" ng-controller="testController as ctrl">
<input type="text" ng-class="ctrl.cssClass" ng-change="ctrl.changeCssInput()" ng-model="ctrl.text"/>
</div>
AngularJS
angular.module('myApp', []).
controller('testController', function ()
{
var ctrl = this;
ctrl.wizard = {
text : '',
cssClass : 'input-red',
changeCssInput : changeCssInput,
};
return ctrl.wizard;
function changeCssInput() {
ctrl.wizard.cssClass = ctrl.wizard.text.length <= 0 ? 'input-red' : 'input-green';
}
});