5

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

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

I tried using elem[0].innerText but it returns the exact binding '{{binding}}' not the value of the binding

.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}}'
        }
    };
});
0

4 Answers 4

6

You can use the $interpolate service, eg

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

Plunker

Sign up to request clarification or add additional context in comments.

Comments

2
 <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 Comment

supposedly i do not want to add any scope attributes? is it posible to get it in another way?
2

During the link phase the inner bindings are not evaluated, the easiest hack here would be to use $timeout service to delay evaluation of inner content to next digest cycle, such as

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

1 Comment

FYI, 0 is the default timeout interval
0

Try ng-transclude. Be sure to set transclude: true on the directive as well. I was under the impression this was only needed to render the text on the page. I was wrong. This was needed for me to be able to get the value into my link function as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.