【问题标题】:Why angular expressions evaluate to empty strings in an attribute为什么角度表达式评估为属性中的空字符串
【发布时间】:2015-11-25 18:08:38
【问题描述】:

当一个元素的属性包含多个角度表达式时,这些表达式的计算结果为空字符串。在我的示例中,我有一个带有 2 个相同表达式的属性,它们都只是输出范围变量。如果我删除一个表达式,则另一个表达式的计算正确。我错过了什么?

从控制器中提取:

$http.get(
    "http://myurl/odata/Profile",
    {
        params: {
            "$orderby": "Id",
            "someParamId": "10"
        }
    }
).success(function (response) {
        $scope.data = response.value;
        $scope.mytest = "hello";
        $scope.dataRead = true;
    }
);

从指令中提取:

    link: function (scope, elem, attrs) {
        scope.$watch("dataRead", function (dataAvailable) {
            if (dataAvailable) {
                ...here I check for mytest attribute value...

从我的 html 中提取:

     <my-directive id="someId" style="position: absolute; background-color:bisque;" width="200" mytest="{{mytest}}{{mytest}}"....

在上面的示例中,如果 mytest 有两次该表达式,则结果值为空字符串,否则计算正确。 因此,基本上一旦在同一属性值中有超过 1 个作用域变量表达式,它就无法评估。

急需帮助!

已编辑:

对迟到的编辑表示歉意。这是显示问题的plunker。 index.html 页面中有一个属性 myattr。它故意将其值设置为两个相同的表达式。然而,在指令的链接函数中,该属性的值是一个空字符串。

【问题讨论】:

  • 代码不完整。我们不知道指令是如何定义的,应该评估什么,评估是什么,在哪里显示,等等。发布一个完整的最小示例来重现问题。解释你期望发生什么,以及会发生什么。
  • 针对您的问题创建一个 plunkr/jsbin/whatever。它在这个中运行良好:jsbin.com/mupuhi/1/edit?html,js,output
  • 是的,很抱歉没有为您提供足够的信息以及延迟回复。这是具有可重现条件的 plunkr:link 如您所见, span 元素确实可以正确评估,但是如果您查看 myattr 属性,它被设置为空字符串 - 一个警告框显示

标签: angularjs scope expression


【解决方案1】:

您的代码有两个问题。

首先,正如我在Angular directive fields not require brackets 中所说。指令字段中的双花括号会导致问题。您应该改用 Angular 表达式。

有问题的 HTML

<body ng-controller="myViewCtrl">
                      <!-- this is a problem -->
    <my-directive myattr="{{mytest}}{{mytest}}"></my-directive>
    <span>{{mytest}}{{mytest}}</span>
</body>

改为使用:

<body ng-controller="myViewCtrl">
    <my-directive myattr="mytest+mytest"></my-directive>
    <span>{{mytest}}{{mytest}}</span>
</body>

第二个问题

要查看属性的计算值,需要使用作用域的$eval方法。

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      scope.$watch("loaded", function(loaded) {
        if (loaded) {
          //Do this
          alert(scope.$eval(attrs.myattr));
          //Not this
          //alert(attrs.myattr);
        }
      });
    }
  }
});

要了解有关$eval 方法的更多信息,请参阅AngularJS $rootScope.Scope API Reference

读者须知

指令ng-srcng-srcsetng-href 被插值并使用双花括号。大多数其他属性指令使用 $eval 来评估 Angular 表达式,并且不适用于双花括号。

双花括号有时在指令中起作用,有时是必需的。这取决于指令的实施方式。所以最终的答案是视情况而定。

【讨论】:

  • 感谢@georgeawg 的示例,但它不相关。请参阅我在原始帖子中的评论。
  • @Nikolai 使用您的代码中的剪辑和更正编辑了答案
  • 就这么简单???! :-$ Das ist fantastische!!!谢谢,我的朋友!删除大括号并使用 $eval 进行评估做得很好!
  • 然而@georgeawg,只是出于兴趣,如果 $scope.mytest 设置在 then 函数之外,为什么相同的表达式会正确计算:app.controller('myViewCtrl', function($scope, jsonService) { $scope.mytest = 'Bzzz'; jsonService.getjson().then(function(d) { $scope.sourceData = d; $scope.loaded = true; }); }); 试试plunker,你会看到 myattr 会正确评估
  • 那是另一个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 2011-06-03
相关资源
最近更新 更多