Search code examples
javascriptangularjsangularjs-directiveangular-directive

Cannot pass boolean to directive with Angular


I'm trying to pass a boolean value from my controller into my isolated scope directive. When I console.log(attrs) from the directive's link function, the someBoolean attribute is a string, rendering the actual text "main.bool" instead of a true or false value. When I toggle the boolean value from the outer controller, I want it to be updated in the directive.

https://plnkr.co/edit/80cvLKhFvljnFL6g7fg9?p=preview

app.directive('myDirective', function() {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        someBoolean: '='
      },
      templateUrl: 'myDirective.html',
      link: function(scope, element, attrs) {
        console.log(scope);
        console.log(attrs);
      },
      controller: function($scope, $element, $attrs) {
        console.log(this);
      },
      controllerAs: 'directiveCtrl',
      bindToController: true
    };
  });

Controller

   app.controller('MainCtrl', function($scope) {
      var vm = this;

      vm.bool = true;
      vm.change = function() {
        vm.bool = !vm.bool;
      }
    });

The template

<div>
  Inside directive: {{someBoolean}}
</div>

Solution

  • As you have attached your directive Controller to directiveCtrl instead of mainCtrl, you'll access the variable someBoolean using directiveCtrl.someBoolean.

    In this case, change the HTML to:

    <div>
      Inside directive: {{directiveCtrl.someBoolean}}
    </div>
    

    Plunker.

    Another solution would be to remove the bindToController property inside your directive. With this, you don't need to use the controller name before the variable. Working Plunker.

    Read more about this bindToController feature here.