anaval anaval - 5 months ago 43
AngularJS Question

how get raw value of angular attribute directive

I want to retrieve the raw value of a directive attribute but it keeps retrieveing the literal attribute name instead of the raw value

--HTML

<input my-directive="5==5" />
<div my-directive="isFoodReady()">
<!--some content-->
</div>


--JS

myModule.directive('myDirective',function(){
restrict: 'A',
priority: 0,
link:function(scope,element,attr){
console.log(attr.myDirective);
//displays "5==5","isFoodReady()" instead of true
}
});

Answer

Here, it's working

angular.module('app', [])
  .directive('myDirective', function() {
    return {
      restrict: 'A',
      priority: 0,
      link: function(scope, element, attr) {
        console.log(eval(attr.myDirective));
      }
    }
  });

function isFoodReady() {
  return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<input my-directive="5==5" />
<div my-directive="isFoodReady()">
  <!--some content-->
</div>
</div>

Keep in mind using eval is extremely dangerous and a terrible practice overall. You shouldn't be running javascript off a directive's attribute since it leaves your code open to even the simples of code injection techniques.

I highly recommend you visit https://xss-game.appspot.com/ to see what I mean