你能从 ngBind 表达式中获取 element.text() 吗?

Can you get element.text() from the from an ngBind expression?

本文关键字:text element 获取 ngBind 表达式      更新时间:2023-09-26

我有一个很大的长哑指令使用ngBindTemplate来完成此操作,但是如果我可以简单地访问表达式中的element.text(),我基本上可以删除该指令。

问:如何从ngBind表达式访问'element.text()'

<h1 ng-bind="worldMapCtrl.header.docs.intro || 'element.text()'">ABC</h1>

不要认为你能做到,对不起!

做了一个测试,无法访问它自己的元素。如果您这样做:

<h1 id="test" ng-bind="worldMapCtrl.header.docs.intro || this.$id">ABC</h1>

然后从控制台执行以下操作:

angular.element(document.getElementById('test')).scope()

并检查$id您会发现它们是相同的。此外,如果您这样做:

angular.element(document.getElementById('test'))

你会看到,即使ng-bind失败了,innerHTML也是空白的。

我做了一个不长的指令,解决了你想要的,如果你仍然想使用指令,让我知道这是否适合你。

(function(angular) {
  'use strict';
  angular.module('app', [])
  .directive('dumbDirective', [function () {
    return {
      restrict: 'AE',
      scope: {
        htmlInput: '='
      },
      controller: SiteMenuController,
      controllerAs: 'vm',
      bindToController: true,
      templateUrl: 'dumb-directive-template.html'
    };
    function SiteMenuController() {
      this.text = angular.element(this.htmlInput).text();
    }
  }])
  .run(['$templateCache', function($templateCache) {
    $templateCache.put('dumb-directive-template.html',
      '{{ vm.text }}'
    );
  }]);
})(window.angular);

指令用法:

// outputs just 'testing'
<dumb-directive html-input="'<span>testing</span>'"></dumb-directive>