选择指令的角度表达式

Angular expression selecting a directive

本文关键字:表达式 指令 选择      更新时间:2023-09-26

我需要呈现一个角度指令,通过调用以前在变量中定义的字符串(通常在控制器中声明)来选择它。尽管这样一个变量可以作为Angular表达式访问,但当我试图使用它来选择指令时,它不起作用:

<!DOCTYPE html>
<html ng-app="app">
<body ng-controller="TextController">
<!-- item.dir is accessible: -->
<div>Value of item: {{item.dir}}</div>
<!-- It works. the directive "hello" is rendered -->
<div class="hello"></div>
<hello></hello>
Here you should see additional text:
<!-- Doesn't work item.dir is not recognized-->
<!-- as a class -->
<div class="{{item.dir}}"></div>
<!-- as an attribute-->
<div {{item.dir}}></div>
<!-- trying ng-class (it fails)-->
<div ng-class="item.dir"></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.5/angular.min.js"></script>
<script>
  var appModule = angular.module('app', []);
  // The directive to render
  appModule.directive('hello', function() {
        return {
          restrict: 'ACE',
          template: '<div>works: Transcoded text</div>',
          replace: true
        };
      });
  appModule.controller('TextController', function ($scope) {
    $scope.item = {dir: 'hello'}; // the name of the directive, the idea is to use it for referring to many future directives.
  });
</script>
</body>
</html>

下面是代码的一个plunker:http://plnkr.co/edit/tM73sY3vTfPFHmn6iCYE?p=preview

那么,我错过了什么?使用指令时,如何使用字符串插值获得Angular?谢谢

要使指令工作,Angular需要编译html(加载页面时自动完成)。

有一种方法可以自由地控制实例化哪个指令,这有点像是小题大做,而且是非典型的。其中一个问题是编译"破坏"了内部绑定/观察者数据和一些原始DOM,因此没有足够的信息来"重新编译"DOM节点。

注意:您不能使用以下类型的绑定来更改具有angular的属性或元素名称(仅属性值):{{}}但是ng class="…"和class="{{…}"有效。

我不明白你到底想达到什么目的。如果真正的意图是修改item.dir的值并让Angular"重新配置"您的应用程序,这是"可能的",但我高度怀疑这会导致"状态"缺陷。

尽管如此,这里有一个有效的"破解",它可以"记住"原始的DOMhtml,并在需要时重新编译它。这分为两个编译阶段:第一阶段是恢复原始绑定,第二阶段在$digest循环之后运行,以便原始绑定完成从作用域填充类名(即使item.dir生效)。当然,缺点是如果您对封闭的DOM进行了修改,这将擦除它们!或者,可以只记住特定的属性,并仅在保持DOM的其他部分不变的情况下恢复"那个"(但可能会产生其他问题)。

  appModule.directive('forceRecompilation', ['$timeout', '$compile', function($timeout, $compile) {
    return {
      restrict: 'A',
      link: function(scope, element, attr) {
        var originalHtml = element.html();
        scope.$watch(attr.forceRecompilation, function(){
            // restore original HTML and compile that
            element.html(originalHtml);
            $compile(element.contents())(scope);
            // wait for all digest cycles to be finished to allow for "binding" to occur
            $timeout(function(){
              // recompile with bounded values
              $compile(element.contents())(scope);
            });
          });
      }
    };
  }]);

用作要操作的DOM部分的封闭标记。当表达式发生变化时,它将"恢复并重新编译"它下面的所有内容。(此处为"item.dir"):

<div force-recompilation="item.dir">
    <div class="{{item.dir}}">
</div>

Plunker:http://plnkr.co/edit/TcMhzFpErncbHSG6GgZp?p=preview

在plunker中,有两个指令"hello"answers"hello2"。将文本更改为"hello"并返回到"hello2"以查看效果。

EDIT:下面是一个指令,允许插入标记,以便按照下面注释中的描述进行编译。这只是Angularjs-inline指令的一个稍微修改过的版本,带有ng-bind-html-insafe-

  angular.module('bindHtmlExample', ['ngSanitize'])
    .controller('ExampleController', ['$scope',
      function($scope) {
        $scope.test = false;
        $scope.dir = "ng-click";
        $scope.clicked = function() {
          $scope.test = !$scope.test
        }
        $scope.myHTML =
          'I am an <b ng-show="test">invisible</b> HTML string with ' +
          '<a href="#" ' + $scope.dir + '="clicked()">links!</a> and other <em>stuff</em>';
      }
    ])
  // modified plunker taken from https://stackoverflow.com/questions/18063280/angularjs-inline-directives-with-ng-bind-html-unsafe
  //
  // Allows an attribute's value to be evaluated and compiled against the scope, resulting
  // in an angularized template being injected in its place.
  //
  // Note: This directive is prefixed with "unsafe" because it does not sanitize the HTML. It is up
  // to the developer to ensure that the HTML is safe to insert into the DOM.
  //
  // Usage:
  //     HTML: <div unsafe-bind-html="templateHtml"></div>
  //     JS: $scope.templateHtml = '<a ng-onclick="doSomething()">Click me!</a>';
  //     Result: DIV will contain an anchor that will call $scope.doSomething() when clicked.
  .directive('unsafeBindHtml', ['$compile',
    function($compile) {
      return function(scope, element, attrs) {
        scope.$watch(
          function(scope) {
            // watch the 'compile' expression for changes
            return scope.$eval(attrs.unsafeBindHtml);
          },
          function(value) {
            // when the 'compile' expression changes
            // assign it into the current DOM element
            element.html(value);
            // compile the new DOM and link it to the current
            // scope.
            // NOTE: we only compile .childNodes so that
            // we don't get into infinite loop compiling ourselves
            $compile(element.contents())(scope);
          }
        );
      };
    }
  ]);
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.5/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.5/angular-sanitize.js"></script>
  <script src="script.js"></script>
</head>
<body ng-app="bindHtmlExample">
  <div ng-controller="ExampleController">
    <p unsafe-bind-html="myHTML"></p>
    (click on the link to see <code>ng-click</code> in action)
  </div>
</body>
</html>

显然,tg动态指令起到了作用。