Matthew Harwood February 2016

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

I have a big long dumb directive using ngBindTemplate to accomplish this but if I could simply access the element.text() inside the expression I could essentially remove the directive.

Question: How do I access 'element.text()' from the ngBind expression?

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

Answers


Nicolas Del Valle February 2016

I made a not that long directive, that solves what you want, in case you still want to use a directive, let me know if this work for you.

(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);

Directive usage:

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


Kristofer Källsbo February 2016

Don't think you can do it, sorry!

Did a test an was unable to access the element it self. If you do:

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

And then from the console do:

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

And check the $id you will see that they are the same. Also if you do:

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

You will see that the innerHTML is blank even if the ng-bind failed.

Post Status

Asked in February 2016
Viewed 3,392 times
Voted 10
Answered 2 times

Search




Leave an answer