I'm trying to add simple ng-mouseover bindings to elements managed by directives. But colud not get it working.
@ http://jsbin.com/aqibij/2/edit
I've tried to recompile the element after adding ng-mouseover binding. directive.compile and outer controller runs, but directive.linker does not run.
@ http://jsbin.com/ikebed/1/edit
I've moved the $compile'ing into linker. It runs fine, ng-mouseover runs fine, but recompiling in linker causes endless loop, which crashes the browser at the end :)
How can I add ng-* bindings to elements using directives? What am I doing wrong in these approaches?
I assumed you were in the same boat as me, but perhaps you aren't. Either way, here are the two solutions. I was stuck on the second.
If you know the element you are dealing with is going to be a div, span, h1, whatever - or it doesn't matter (taking one element and replacing it with what you need it to be).
<div data-mydirective>
    <span>some other stuff</span>
    <div>more stuff</div>
</div>
module.directive( 'mydirective', [ function() {
    return {
        restrict: "A",
        controller: function( $scope ) {
            $scope.test = function() {
                console.log('howdy');
            }
        },
        template: "<div data-ng-transclude data-ng-mouseover='test()'></div>",
        transclude: true,
        replace: true,
        link: function ( scope, element, attrs ) {
        }
    };
}]);
<div ng-mouseover="test()" data-ng-transclude="" data-mydirective="">
    <span class="ng-scope">some other stuff</span>
    <div class="ng-scope">more stuff</div>
</div>
This is the problem I was facing. Basically, if you have a directive which could be on an h1, h2, span, div, nav, etc and you want to add your ng-* and attributes from within the directive. 
You can't use a template because you don't know what the element is. Don't want to take a h1 and replace it with a div right? This is why I was going down the compile route. Well, the template can actually be a function which we can access element and attrs.
module.directive( 'mydirective', [ function() {
    return {
        restrict: "A",
        controller: function( $scope ) {
            $scope.test = function() {
                console.log('howdy');
            }
        },
        template: function( element, attrs ) {
            var tag = element[0].nodeName;
            return "<"+tag+" data-ng-transclude data-ng-mouseover='test()></"+tag+">";
        },
        transclude: true,
        replace: true,
        link: function ( scope, element, attrs ) {
        }       
    }   
}]);
Same as above. Change the div element in your HTML to a nav, and the output will mirror the change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With