简体   繁体   中英

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

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
          }
      }
  });

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>

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.

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
          }
      }
  });

I was able to get it working like this:

let replicateReopeningClientFiles = @Json.Serialize(Model.ReplicateReopeningClientFiles);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM