Peter Boomsma
Peter Boomsma

Reputation: 9844

How to pass value into directive?

I have button in my html which has a directive on it. I would like to pass a value to that directive:

<md-button class="md-icon-button" minimize-popup mdMenu="$mdMenu">

In my directive I have:

return {
    scope: {
        mdMenu: '='
    },
    link (scope, element, attrs) {
        console.log(scope.mdMenu);

But the log shows the line as undefined. I guess it's because the the minimize-popup and the mdMenu=$mdMenu have no relation to each other.

Upvotes: 0

Views: 74

Answers (1)

lenilsondc
lenilsondc

Reputation: 9810

First, your parameter name has to be normalized to md-menu otherwise angularjs will normalize it to mdmenu which will never match mdMenu within the directive definition.

Second, make sure $mdMenu is defined on your scope; because angularjs will look for a variable in scope since you made the bind like mdMenu: '='.

Bellow there is a simple snippet with a directive with parameter for you to use as an example.

angular.module('app', [])
  .directive('myDirective', function () {
    return {
      scope: {
        'myParam': '='
      },
      link(scope, elem, attrs){
        console.log(scope.myParam)
      }
    }
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.js"></script>
<div ng-app="app" ng-init="test = 'foo'">
  <div my-directive my-param="test"></div>
</div>

Upvotes: 2

Related Questions