Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

passing data through Angular custom directive


I created a custom directive in angular. I would like to pass parent data through the directive using scope but I'm getting 'undefined' when I log scope and scope.questionId.

HTML

<a class="waves-effect waves-light btn" my-directive="" on-flag="someFunction" question-id="question">Flag</a>

Angular Directive

angular.module('myApp').directive('myDirective', function($http) {
  return {
    restrict: 'A',
    scope: {
      onFlag: '&onFlag',
      questionId: '='
    },
    link: function(scope, element, attrs) {
      element.click(function() {
        console.log(scope);
        console.log(scope.questionId);
        return;
      });
    }
  };
});

Solution

  • Try this

    elem.bind:- It uses the JQLite which is lite version of JQuery. Here we are writing the code to handle the click event performed on the directive. It is same like JQuery $("class or id").click(). (I hope this explains is sufficient)

    angular.module('myApp').directive('myDirective', function($http) {
      return {
        restrict: 'A',
        scope: {
          onFlag: '&onFlag',
          questionId: '='
        },
        link: function(scope, elem, attrs) {
         		elem.bind('click', function() {
            	console.log(scope.questionId);
          });
        }
      };
    });