Smeegs Smeegs - 2 months ago 17
AngularJS Question

Angular directive with bool attribute passing string instead of bool

I'm trying to create a directive that will disable all the input elements inside of the container, but I'm having trouble with the attribute. This is what I've got for the directive


.directive('bdDisabled', [function () {
return {
restrict: 'A',
scope: {
bdDisabled: '='
link: function (scope, element, attrs) {
attrs.$observe('bdDisabled', function(newValue, oldValue) {
if (newValue !== oldValue) {
if (newValue) {
element.find('input, select, button, submit, textarea').prop('disabled', 'disabled');
} else {
element.find('input, select, button, submit, textarea').removeProp('disabled');


This is how I want to use it:

<div class="cg-content cg-shadow" bd-disabled="isLoading">

The problem is that the attribute value is the string
and not the value.

If I wrap it in braces it breaks and I get an error in the console.
If I wrap it in braces and change the scope to '@' instead of '=', it works. But it sends the string "true" or "false", not a boolean value.

Where am I going wrong?


As I suggested in the comment, I'd switch the attrs.$observe with scope.$watch. On a personal preference, I'd also use the function expression instead of a string, since if you're using typescript for instance (or will use) you'll be notified if the property changes, where a string will probably remain as it is:

scope.$watch(function () {
      return scope.bdDisabled;
      function (newVal, oldVal) {