Angular错误解析

Angular Error Parsing ng-show

本文关键字:误解 错误 Angular      更新时间:2023-09-26

我在index.html中的div上有一个ng-show,它决定根据用户清除显示哪个标头。这些清除存储在$scope.user中。作为清除对象的数组。scope.user美元。清除的结构如下:

[
    {
       'clearance':string
    }
]

导致解析错误的指令是:

<div ng-show = "user.clearance &&
        user.clearance.filter(function(e) { return e['clearance'] === 'SUPERADMIN'; }).length > 0" 
        ng-include="'/partials/components/superadmin-header.html'">
</div>

表达式:

user.clearance && user.clearance.filter(function(e) { 
     return e['clearance'] === 'SUPERADMIN'; 
}).length > 0

在jsfiddle: http://jsfiddle.net/6frqzwee/2/

中正常工作

你知道为什么angular在这方面有困难吗?

因为ng-show指令将 $watch放在您在ng-show属性上提供的expression上。如果你将表达式作为string传递,它将在当前范围内计算它们,但是当你传递带有属性的函数时将抛出$parse错误。

更好地使它工作,你可以有角过滤器|,它会给你预期的结果,不会抛出任何错误,而解析HTML

<div ng-show ="user.clearance &&
    (user.clearance | filter: {clearance: 'SUPERADMIN' }).length > 0" 
    ng-include="'/partials/components/superadmin-header.html'">

与上面的语法一样,(user.clearance | filter: {clearance: 'SUPERADMIN' })将使用作用域进行计算,它将返回具有clearance属性值与SUPERADMIN匹配的元素数组。