Dean Christian Armada Dean Christian Armada - 6 months ago 28
AngularJS Question

ng-show with form condition not working on a directive template in AngularJS

In the directive I was wondering why the CSS is not reacting accordingly to the attributes. My ng-show is a simple boolean condition that depends if the required error of a certain input is true or not. In short what I want is while the required validation is true the take exam must be hidden until the user inputs something on the textbox

Here is the code:

<!DOCTYPE html>
<html ng-app="myApp">

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>

<body>
<div class="container">
<div id="login-container">
<div class="form-group">
<span class="glyphicon glyphicon-user"></span>
</div>
<form name="loginForm" novalidate>
<div class="form-group">
Required condition -- {{ loginForm.student_code.$error.required }}
<!-- dasdas -- {{loginForm.student_code.$error.codeValidity }} -->
<br />
<input type="text" class="form-control text-center" name="student_code" ng-model="studentCode" placeholder="Enter Exam Code" required />
<!--<span class="errors" id="error-student-code" ng-if="loginForm.student_code.$error.codeValidity">{{ errors }}</span>-->
</div>
</form>
<login-button form="loginForm"></login-button>
<a href="register"><button class="btn btn-primary">Register</button></a>
<!-- <br /> <strong>A message must be seen after the colon if codeValidity is true: </strong> -->
</div>
</div>
</body>
<script>
var app = angular.module("myApp", []);

app.directive('loginButton', loginButton);

loginButton.$inject = ["$http", "$window"];

function loginButton($http, $window){
return {
scope: {
form: '='
},
template: '<button type="button" class="btn btn-primary" ng-show="{{ !form.student_code.$error.required }}" ng-click="click()">Take Exam</button>',
controller: function($scope){
$scope.click = function(){
form = $scope.form;
form.student_code.$setValidity('codeValidity', false);
$scope.errors = "Code is Invalid";
};
}
}
}
</script>
</html>


Here is the plunker: https://plnkr.co/edit/plpKSGBtWqQnzhL60OfJ?p=preview

Answer

You are incorrectly trying to interpolate the variable inside the ng-show, but ng-show takes an expression. Interpolated values aren't evaluated in time for their value to be reflected by the ng-show directive. Instead, you should allow ng-show to evaluate the expression and interpolate it if necessary.

i.e. instead of: ng-show="{{ !form.student_code.$error.required }}",

do: ng-show="!form.student_code.$error.required".