Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element.find does not work for nested elements inside ng-switch

I have a directive that contains an ng-switch DOM element. I need to bind an event to a DOM node under the ng-switch, but for some reason element.find does not return any nodes under the switch element!

In the example below, I expect element.find("*") to return ng-switch, one div and the button yet it only returns ng-switch and the button.

How can I solve this? Or reach DOM nodes under ng-switch from the link function a different way?

Code to reproduce:

HTML

<div ng-controller="myCtrl" class="container">
    <div my-directive>
        <ng-switch on="selection">
            <div ng-switch-when="A" class="a">A</div>
            <div ng-switch-when="B" class="b">B</div>
            <div ng-switch-default>default</div>
        </ng-switch>        
        <button ng-click="switchSelection()" >switch</button>
    </div>
</div>

JS

angular.module('myApp', [])
    .directive("myDirective", function () {
    return {
        link: function(scope, element, attrs) {
            console.log(element.find("*"));
            console.log("Didn't find my divs :(");
        }
    }
});


function myCtrl($scope) {
    $scope.selection="B";

    $scope.switchSelection=function(){
        if ($scope.selection=="B"){
            $scope.selection="A";
        }
        else{
            $scope.selection="B";
        }
    }
}

jsFiddle example

like image 460
OpherV Avatar asked Jan 17 '26 21:01

OpherV


1 Answers

Based on your question in the comment asking how to bind a load event to the image if it's within a switch.

What you can do is create a directive for the images and then bind the load event within the linking function

.directive("myImageDirective", function(){
    return {
        restrict: 'C',
        link: function(scope, element){
            element.bind("load", function(){
                console.log("element loaded");
                scope.$apply();
            });
        }
    };
});

jsfiddle: http://jsfiddle.net/kB4vq/

The scope.$apply(); is to let angular know to re-process itself if you need it too, since the load happens outside of angular's knowledge. You can read up more on that here: http://docs.angularjs.org/api/ng.$rootScope.Scope#$apply

like image 166
Mathew Berg Avatar answered Jan 20 '26 10:01

Mathew Berg