重构 AngularJS 以使用 controllerAs,一旦输入不为空,就将 CSS 应用于所需的输入

Refactor AngularJS to use controllerAs, apply CSS for a required input once it is not empty

一旦使用 AngularJS 1.5.6 有效,有条件地更改所需输入的背景颜色的最有效方法是什么?根据我的理解和我所拥有的 read online,我应该避免使用 $scope 而是使用 controllerAs。我将如何重构为以下 AngularJS 代码以使用 controllerAs?

只有 CSS 和 HTML

HTML

<input id='textfield' placeholder='Search'  required>

CSS

#textfield:valid {
    background-color: green;
    color: white;
}

使用 $scope

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?

(以下代码是使用controllerAs语法编写的,有关controllerAs语法的更多信息,请参见下文)

<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?

使用 controllerAs 语法

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';  
    }
});