1

Directive usage

<my-directive my-attr='StackOverflow'></my-directive>

Directive definiton

app.directive('myDirective', function($scope){
  return {
    restrict: 'E',
    template: 'I want to print the attribute value',
    controller: function($scope){
      // I also want to access the attribute value here.
    }
  };
});

Is there a way to achieve this.

Shreyas
  • 1,927
  • 17
  • 34

2 Answers2

2

Instead of scope: true write,

scope: {
  myattr: '@'
}

Then myattr will be available in $scope

Fiddle

Make sure to use small casing, somehow using any other casing like pascal or camel causes problems.

Shreyas
  • 1,927
  • 17
  • 34
1

Yes you can pass values to directive using scope.

your code can be written something like

   app.directive('myDirective', function($scope){
    return {
      restrict: 'E',
      Scope:{
        myAttr:'='
      },
      template: 'I want to print the attribute value: and here is your value: {{myAttr}}',
      controller: function($scope){
       // I also want to access the attribute value here.
        console.log($scope.myAttr);
      }

}; });

and usage is same

<my-directive my-attr='StackOverflow'></my-directive>

Here is same question Angularjs - Pass argument to directive

Also you can find more information on usage of directive at https://docs.angularjs.org/guide/directive

Community
  • 1
  • 1
Shankar D
  • 94
  • 4