一旦使用AngularJS 1.5.6有效,最有效地更改背景颜色的最有效方法是什么?根据我的理解以及我在线阅读的内容,我应该避免使用$范围,而是使用控制器。我如何重构AngularJS代码使用控制器?
只有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';
}
});
有条件地更改的最有效方法是 一旦使用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 语法
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';
}
});