Angularjs directive - get text content of bound element

How do you get the binding value based on the angular js directive restrict: 'A'

?

<span directiverestrict> {{binding}} </span>

      

I tried using elem[0].innerText

but it will return the exact binding '{{binding}}'

, not the binding value

.directive('directiverestrict',function() {
    return {
        restrict:'A',
        link: function(scope, elem, attr) {
            // I want to get the value of the binding enclosed in the elements directive without ngModels
            console.log(elem[0].textContent) //----> returns '{{binding}}'
        }
    };
});

      

+3


source to share


3 answers


You can use a service $interpolate

like

.directive('logContent', function($log, $interpolate) {
  return {
    restrict: 'A',
    link: function postLink(scope, element) {
      $log.debug($interpolate(element.text())(scope));
    }
  };
});

      



Plunker

+5


source


During the link phase, internal bindings are not evaluated, the simplest hack here would be to use a service $timeout

to delay evaluating internal content for the next digest cycle, for example



$timeout(function() {
   console.log(elem[0].textContent);
},0);

      

+2


source


 <span directiverestrict bind-value="binding"> {{binding}} </span>

      

SCRIPT

directive("directiverestrict", function () {
   return {
           restrict : "A",
           scope : {
                      value : '=bindValue'
                   },
           link : function (scope,ele,attr) {
                alert(scope.value); 
              }
      }
});

      

+1


source







All Articles