【问题标题】:How can I pass a Razor boolean variable to an Angular directive?如何将 Razor 布尔变量传递给 Angular 指令?
【发布时间】:2016-07-22 11:57:43
【问题描述】:

我的 cshtml 文件中有一个布尔变量。当我尝试将它传递给我的 Angular 指令时,它被接收为“假”而不是“假”。如果我将它硬编码为“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
          }
      }
  });

【问题讨论】:

    标签: javascript c# angularjs razor boolean


    【解决方案1】:

    您可以找到部分答案here

    特别是对于 Angular,使用指令变量 test: '=' 而不是 test: '@'。这样,您的变量将被解析为值为“false”的 boolean,而不是 text“false”。

    另外,在您的 Razor 文件中,尝试以下操作将“假”转换为“假”:

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

    【讨论】:

    • 如果您使用的是返回 True 或 False 的函数,我也可以将上述内容与 &lt;my-directive my-boolean="@MyFunctionReturnsTrue().ToString().Tolower()"&gt;&lt;/my-directive&gt; 一起使用。
    【解决方案2】:

    由于两种语言都区分大小写并且对布尔值使用不同的模式(即使是数字),您可以使用:

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

    将 C# 数据相应地格式化为 javascript。

    【讨论】:

    • 但是,我很确定您还需要使用 = 绑定。使用@ 会将布尔值视为字符串。
    【解决方案3】:

    您的范围应该是 '=' 而不是 '@'

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

    【讨论】:

      猜你喜欢
      • 2015-09-08
      • 2012-02-21
      • 2018-02-17
      • 2013-04-20
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      相关资源
      最近更新 更多