1
votes

I have created a angularjs directive that are supposed to display an address.

$(elem).find('button').length

now return the correct value but it have been called a hack and is there a better way to do it. I understand that ngIf creates a child scope and the button element isn't available when my link code runs if I don't wrap it in $timeout.

So what is the pretty way to access the element inside my ngIf without the $timeout hack?

My Directive

angular.module('directives')
.directive('addresss', ['$timeout', function ($timeout) {

    return {
        restrict: 'AE',
        scope: {
            address: '='
        },
        templateUrl: 'template........ ',
        link: function(scope,elem,attr){
            $timeout(function(){
                console.log($(elem).find('button').length);
            })
        }

    };
}]);

Template for address directive

<div class="spacer">
    <h1>Address</h1>

    <div>
        <strong>{{address.name}}</strong>
    </div>
    <div ng-if="address.name">
        <button class="btn-link">Delete</button>
    </div>

</div>
2
what is overall objective apart from finding length?charlietfl
@charlietfl I just need that button to attach a click event. I can do that now but are looking for better solution.pethel
imo you've got all you need in the directive put the if in it :)Whisher
get rid of the jQuery approach and just use ng-clickcharlietfl

2 Answers

1
votes

if all you want to bind a click event you could just put a ng-click in the button:

JS:

app.directive('address', [function () {

    return {
        restrict: 'AE',
        scope: {
            address: '='
        },
        templateUrl: 'template.html ',
        link: function(scope,elem,attr){
          scope.myClickHandler = function() {
            console.log('button clicked');
          });
        }

    };

Template:

<div class="spacer">
    <h1>Address</h1>

    <div>
        <strong>{{address.name}}</strong>
    </div>
    <div ng-if="address.name">
        <button ng-click="myClickHandler()" class="btn-link">Delete</button>
    </div>

</div>
0
votes

Try this (if I get well your question)

html

<div data-ng-controller="MainController">
  <div data-my-dir address="address"></div>
</div>

js

angular.module('myApp', [])
.controller('MainController',function($scope) {
    $scope.address = {
        name : 'myname'
    };
})
.directive("myDir", function () {
    return {
        scope:{
            address: '=',
        },
        template:'<button class="btn-link" ng-if="address.name">Delete</button>',
        link: function (scope, elem) {
            console.log(scope.address.name);        
        }
    }
 });