Shreyas
Shreyas

Reputation: 1937

Passing attribute value to directive controller

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.

Upvotes: 1

Views: 4867

Answers (2)

Shreyas
Shreyas

Reputation: 1937

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.

Upvotes: 2

Shankar D
Shankar D

Reputation: 94

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

Upvotes: 1

Related Questions