How to check in an Angular directive if the parent node is a link?

1

I need to check if my xx-chip directive is inside a link. I can not use jQuery in this application, only Angular.

<a href>
    <xx-chip></xx-chip>
</a>

Thank you.

    
asked by anonymous 05.05.2016 / 13:55

2 answers

0

After an analysis and some console.log in the code, I was able to find the solution that I was longing for:

angular
    .module('xx.chip', [])
    .directive('xxChip', chip);

function chip() {
    var directive = {
        ...
    };

    return directive;

    function link(scope, element) {
        // Remove o underline do elemento pai se for um link
        if (element.parent()[0].localName === 'a') {
            element.parent().css('text-decoration', 'none');
        }
    }
}

I hope it helps other developers.

    
06.05.2016 / 00:18
0

I think this is the best answer, it will help you solve, it is exactly what you want only using the most usual expression (parent and child), as conventionally we use (SO-eng):

HTML

<div ng-app ng-controller="ParentCtrl as pc">
    <div ng-controller="ChildCtrl as cc">
        <pre>{{cc.parentCities | json}}</pre>
        <pre>{{pc.cities | json}}</pre>
    </div>
</div>
JS

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl() {
    var vm = this;
    ParentCtrl.apply(vm, arguments); // Inherit parent control

    vm.parentCities = vm.cities;
}

If you use the controller as a method you can also access the parent scope as follows:

function ChildCtrl($scope) {
    var vm = this;
    vm.parentCities = $scope.pc.cities; //Note que PC é uma referência para o "ParentCtrl como pc"
}

As you can see, there are many different ways to access '$ scope' scopes.

Fiddle:

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl($scope) {
    var vm = this;
    ParentCtrl.apply(vm, arguments);

    vm.parentCitiesByScope = $scope.pc.cities;
    vm.parentCities = vm.cities;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script><divng-appng-controller="ParentCtrl as pc">
  <div ng-controller="ChildCtrl as cc">
    <pre>{{cc.parentCities | json}}</pre>
    <pre>{{cc.parentCitiesByScope | json }}</pre>
    <pre>{{pc.cities | json}}</pre>
  </div>
</div>

Original: link

    
05.05.2016 / 16:16