1

一旦使用 AngularJS 1.5.6 有效,有条件地更改所需输入的背景颜色的最有效方法是什么?根据我的理解和在线阅读的内容,我应该避免使用 $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';  
    }
});
4

1 回答 1

1

一旦使用 AngularJS 1.5.6 有效,有条件地更改所需输入的背景颜色的最有效方法是什么?

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

<input type="text" ng-class="ctrl.text.length <= 0 ? 'input-red' : 'input-green'" ng-model="ctrl.text"/>

我将如何重构以下 AngularJS 代码以使用 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';  
    }
});
于 2017-09-22T14:09:00.430 回答