【问题标题】:AngularJS - Using a comma or other special character in expression to watch with $scope.$watchAngularJS - 在表达式中使用逗号或其他特殊字符来观察 $scope.$watch
【发布时间】: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


【解决方案1】:

由于attrs.authIf 是无效表达式,您可以将其包装在一个函数中

scope.$watch(function() { return attrs.authIf; }, checkAuth);

工作example

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>

    <script>
      angular
        .module('app', [])
        .controller('appCtrl', function($scope) {
          $scope.dir = 'initial value';
        })
        .directive('dir', function() {
          return {
            restrict: 'A',
            scope: true,
            link: function(scope, element, attrs) {
              scope.$watch(function() {
                return attrs.dir;
              }, function(newValue) {
                scope.custom = 'custom ' + newValue;
              });
            }
          };
        });
    </script>
  </head>

  <body ng-controller="appCtrl">
    <h1>Hello Plunker!</h1>

    <div dir="id=12345;CREATE,READ,UPDATE">
      {{ custom }}
    </div>

    <hr>

    <div dir="{{ dir }}">
      {{ custom }}
    </div>

    <input type="text" ng-model="dir">
  </body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-19
    • 2014-04-11
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多