簡體   English   中英

如何將 Razor boolean 變量傳遞給 Angular 指令?

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

我的 cshtml 文件中有一個 boolean 變量。 當我嘗試將它傳遞給我的 Angular 指令時,它被接收為“False”而不是“false”。 如果我將它硬編碼為“false”(小寫),它也不起作用。

我的 cshtml 文件:

@{
    var myVar = false;
}

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

我的測試指令是這樣的:

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

你可以在這里找到你的部分答案。

特別是對於Angular,使用指令變量作為test: '='而不是test: '@' 這樣,您的變量將被解析為值為“false”的布爾值,而不是文本 “false”。

此外,在您的Razor文件中,嘗試以下操作將“False”轉換為“false”:

@{
    var myRazorVar = false;
}

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

由於兩種語言都區分大小寫並且使用不同的布爾模式(即使對於數字),您可以使用:

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

將C#數據格式化為javascript。

你的范圍應該是'='而不是'@'

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

我能夠讓它像這樣工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM