3

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
          }
      }
  });
Zanon
  • 29,231
  • 20
  • 113
  • 126
rajesh
  • 41
  • 7

4 Answers4

5

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>
Community
  • 1
  • 1
Zanon
  • 29,231
  • 20
  • 113
  • 126
  • 1
    If you're using a function that returns True or False, I was able to use the above just with `` as well. – Mattkwish Jun 28 '18 at 14:06
  • It does work but seems weird that you need to cast it to a string and then to lower to make the directive understand that its a boolean value. Surely there's a way to just send the boolean? Even 6 years later it does not seem straightforward! – Dermo909 May 13 '22 at 10:51
3

Since both languages are case sensitive and uses different pattern for Boolean (even for numbers) you can use:

<some-directive test="@Json.Encode(myVar)"></some-directive>  

Will format C# data to javascript accordingly.

Anupam Singh
  • 1,158
  • 13
  • 25
  • 1
    However, I'm pretty sure that you also need to use the `=` binding. Using `@` will treat the boolean as a string. – Zanon Apr 02 '16 at 18:59
1

your scope should be '=' not '@'

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) // true
              console.log(!!$scope.test) // false
          }
      }
  });
Zanon
  • 29,231
  • 20
  • 113
  • 126
Venkat
  • 551
  • 6
  • 17
0

I was able to get it working like this:

let replicateReopeningClientFiles = @Json.Serialize(Model.ReplicateReopeningClientFiles);
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480