Reputation: 363
I'm doing the next thing. I want to enter empty values in input its boundary highlighted (added new class 'warning'). I created the following code.
HTML:
`<body ng-app="TestPage">
<form ng-controller="TestForm">
<input ng-model="testinput" class="form-input" ng-class="testclass" type="text"/>
<button ng-click="submitButton()">Click</button>
</form>
</body>`
JavaScript:
`angular.module('TestPage',[])
.controller('TestForm', function($scope, $animate) {
$scope.submitButton = function() {
if (($scope.testinput == undefined) || ($scope.testinput == "")) {
$animate.addClass($scope.testclass, "warning");
}
};
});`
But the use of the addClass
does not work. What am I doing wrong?
Upvotes: 0
Views: 730
Reputation: 612
According to the document
the service $animate's addClass function has three parameters;
First params is the element which the CSS classes will be applied to.
Second params is the CSS class(es) that will be added (multiple classes are separated via spaces)
Third params is an optional collection of options/styles that will be applied to the element.
so your should try to do it :
html:
`<body ng-app="TestPage">
<form ng-controller="TestForm">
<input id="target_element" ng-model="testinput" class="form-input" ng-class="testclass" type="text"/>
<button ng-click="submitButton()">Click</button>
</form>
</body>`
javascript:
`angular.module('TestPage',[])
.controller('TestForm', function($scope, $animate) {
$scope.submitButton = function() {
if (($scope.testinput == undefined) || ($scope.testinput == "")) {
$animate.addClass(angular.element('#target_element'), "warning");
}
};
});`
A better approach is to use the directive.
module.directive('addClassBy',['$animate',function($animate){
return function(scope,element){
scope.$watch('testinput',function(newValue,oldValue){
if(newValue === oldValue){return};
if(newValue === undefined || newValue === ''){
$animate.addClass(element,'warning')
}
})
}
}])
then html:
`<body ng-app="TestPage">
<form ng-controller="TestForm">
<input add-class-by ng-model="testinput" class="form-input" ng-class="testclass" type="text"/>
<button ng-click="submitButton()">Click</button>
</form>
</body>`
Upvotes: 1