Dean Christian Armada Dean Christian Armada - 2 years ago 80
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">

<script src=""></script>

<div class="container">
<div id="login-container">
<div class="form-group">
<span class="glyphicon glyphicon-user"></span>
<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>-->
<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> -->
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){
$ = function(){
form = $scope.form;
form.student_code.$setValidity('codeValidity', false);
$scope.errors = "Code is Invalid";

Here is the plunker:

Answer Source

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".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download