Search code examples
javascriptangularjsangular-directive

How to access elements attributes from custom directive while keeping access to parent scope?


Essentially I want to be able to access the parent scope of the directive I have created, but I also want to be able to access the attributes that I have placed onto the element.

For example relevant js

app.directive('testDirective', function(){
    return {
        restrict:"E",
        templateUrl:"directive.html",
        scope:{
            testAttribute: '='
        }
    };
});

app.controller('mainCtrl', function($scope){
     $scope.name = 'henry'
}

index.html

<div ng-controller="mainCtrl">
    <test-directive test-attribute="Hello"></test-directive>
</div>

directive.html

{{testAttribute}}
{{name}}

Output is "Hello" instead of "Hello Henry"

So just to clarrify, All I want to be able to do is access the attributes and the parent scope.


Solution

  • For what you are trying to do, do not need a two way binding. You are trying to access the text assigned as attribute. You could just write your directive as:-

    .directive('testDirective', function(){
        return {
            restrict:"E",
            //scope:true,   //apply if required
            templateUrl:"directive.html",
            link:function(scope, elm, attrs){
               scope.testAttribute = attrs.testAttribute; //Get it from attributes
            }
        };
    });
    

    Demo

    Now here scope property of directive settings is going to use the parent scope itself. But ideal scenarios you may want to use scope:true (Child scope of parent) or a 2 way binding wit isolated scope. But at this point, since not really sure what is your original goal, this is a solution based on what you have in your question.

    So to summarize:-

    I want to be able to access the parent scope of the directive I have created

    Remove the isolated scope and just use parent's scope.

    but I also want to be able to access the attributes that I have placed onto the element.

    Use attrs argument of the link function (attrs.testAttribute). If you want to evaluate it as a bound value the do (scope.$eval(attrs.testAttribute))