【发布时间】:2016-02-27 16:08:37
【问题描述】:
我有一个不久前编写的指令,并已在我的整个应用程序中使用。我现在意识到它需要一个手表,以便它可以在值更改时刷新和更新。
这是一个属性指令,用于根据用户的授权应用 Angular 的 ngIf 指令。在 HTML 中使用它看起来像:
<div auth-if="id=12345;CREATE,READ,UPDATE"></div>
我遇到的问题是逗号 - 当我尝试查看 authIf 的属性值时出现错误
错误:[$parse:syntax] 语法错误:标记 ',' 是意外标记
现在我不知道为什么我不只使用字母 CRUD,但我不想更改指令接受的内容并可能破坏事物或引起混乱等。
所以我想知道是否有办法让 Angular 对逗号感到满意?
这是我的指令的简化版本:
angular.module("myApp").directive("authIf", ["ngIfDirective", "IsAuthorised", function(ngIfDirective, IsAuthorised)
{
var ngIf = ngIfDirective[0];
return {
restrict: "A",
priority: ngIf.priority - 1,
terminal: ngIf.terminal,
transclude: ngIf.transclude,
link: function(scope, element, attrs)
{
var permitted = false;
// run angular ngIf functionality
attrs.ngIf = function() {
return permitted;
};
ngIf.link.apply(ngIf, arguments);
scope.$watch(attrs.authIf, checkAuth);
function checkAuth() {
/** check goes here
permitted = IsAuthorised(...); **/
}
}
};
});
【问题讨论】:
-
试试
attrs.$observe而不是scope.$watch -
id=12345;CREATE,READ,UPDATE不是有效的Angular expression -
attrs.$observe 仅适用于我认为的插值...我确实尝试过,但发生变化时它不会运行
-
attrs.$observe 应该这样做。但是只有使用插值时才会注意到变化,例如
auth-if="{{myModel}}" -
但这不是意味着更新所有使用该指令的地方吗?这就是我要避免的,我希望我可以在指令代码中进行一些更改
标签: angularjs parsing angularjs-scope watch angular-directive