How can I pass a Razor boolean variable to an Angular directive?

Issue

I have a boolean variable in my cshtml file. When I try to pass it to my Angular directive, it is received as “False” instead of “false”. If I hardcode it to “false” (lower case), it does not work either.

My cshtml file:

@{
    var myVar = false;
}

<some-directive test="@myVar"></some-directive>

My test directive is like this:

angular.module('someApp')
  .directive('someDirective', function () {
      return {
          restrict: 'E',
          scope: {
              test: '@'
          },
          link: function ($scope, element, attrs) {

              console.log($scope.test) // False
              console.log(!$scope.test) // false
              console.log(!!$scope.test) // true
          }
      }
  });

Solution

You can find part of your answer here.

Specifically for Angular, use the directive variable as test: '=' instead of test: '@'. With this, your variable will be parsed as a boolean with the value “false” and not as the text “false”.

Also, in your Razor file, try the following to convert from “False” to “false”:

@{
    var myRazorVar = false;
}

<some-directive test="@myRazorVar.ToString().ToLower()"></some-directive>
@* or *@
<some-directive test="@Json.Encode(myRazorVar)"></some-directive>

Answered By – Zanon

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.