Thorium Thorium - 10 months ago 32
AngularJS Question

AngularJS - My error messages aren't updating when their trigger variables are changed in the scope?

I'm pretty new to Angular so this is probably a really simple question with a really obvious answer, but I haven't been able to work it out from reading through similar posts so I figured I'd ask here.

Basically I have a text input field, and I'm trying to make an error message appear/dissapear beneath it in real time depending on whether it does or doesn't have any content in it (I also have other fields with different error messages that will appear/dissapear based on different criteria though, so just setting it as a required field as a quick fix won't work for my other other purposes)

As far as I can tell, the trigger variable is updating exactly as it should when I enter or delete text, but the error message itself apparently isn't getting the memo and is just staying as it is.

Here's a cut down version of what I have so far


<div class="col-sm-12">
<form class="form-horizontal" autocomplete="off" name="createRiskAssessmentForm">
<div class="form-group">
<label for="inputRiskNameId" class="col-sm-2">Name:</label>
<div class="col-sm-6">
<input id="inputRiskNameId" class="form-control" type="text" ng-model="" name="riskNameField">
<div ng-hide="$scope.nameFieldHasContent" class="alert alert-danger">This field is required!</div>


'use strict'

module.exports = function (module) {
module.controller('CreateRiskAssessmentTableController', ['$scope', '$rootScope', function($scope, $rootScope) {

$scope.$watch('', function(name) {
if (name == '') {
$scope.nameFieldHasContent = false;
else {
$scope.nameFieldHasContent = true;
console.log('Name field has content?: ' + $scope.nameFieldHasContent);


What am I doing wrong?

Answer Source

I dont think this line is correct:

<div ng-hide="$scope.nameFieldHasContent" class="alert alert-danger">This field is required!</div>

remove the '$scope.' part on ng-hide, changing it to:

<div ng-hide="nameFieldHasContent" class="alert alert-danger">This field is required!</div>

You could also checkout the angular directives ng-dirty and ng-valid to help with this.