jeudi 16 juin 2016

Angular custom 'A' directive not dynamic, not updating

I want to make a dynamic attribute directive on a parent div. I am using a directive within a directive, and the child directive inherits the scope from the parent.

The attribute should tell the child directive to change the background image upon the click of an arrow key (imitating audio volume control). The background image is set upon the state loading, but afterwards the attribute is static and not changing.

The console logs every keydown event from the parent directive and the value of scope.volumeIMG changes, but in the child directive only reads at the state initializing and so the image never changes.

How can I make the background-image dynamic? What am I doing wrong?

The name of the parent directive is displayVolumeModal, the child is backgroundVolumeDirective

displayVolumeModal.html - this is a partial called in the parent template with the element <display-volume-modal>

<div class="display-volume-modal" id="displayVolumeModal">
    <div background-volume-directive="{{volumeIMG}}" class="display-volume-box">
    </div>
</div>

backgroundVolumeDirective

angular.module('app').directive('backgroundVolumeDirective', function(){
    function linker(scope, elem, attrs){
        attrs.$observe('backgroundVolumeDirective', function(val){
            elem.css({
                'background-image': val
            });             
        });     
    }
    return {
        restrict: 'A',
        replace: true,
        scope: false,
        link: linker
    };
});

displayVolumeModal.js

// Only relevant code included
 return {
    restrict: 'E',
    scope: false,
    link: function(scope, elem, attrs){

        function volumeIMG(img){
            return img;
        }

        var imageNum = 5;
        if(scope.volumeIMG === (null || undefined)){
            var IMG = "url('public/images/Audio/I_Audio_VolumeLevel_5.png')";
            scope.volumeIMG = volumeIMG(IMG);
        }

        function downUp (str){
            switch(str){
                case "up":
                    if (imageNum !== 11){
                        imageNum += 1;
                        IMG = "url('public/images/Audio/I_Audio_VolumeLevel_" + imageNum + "'.png')";
                        scope.volumeIMG = volumeIMG(IMG);
                    } else {
                        scope.volumeIMG = scope.volumeIMG;
                    }
                    break;
      // Other stuff happens in this function

            }
        }

        document.addEventListener('keydown', function(e){
            switch (e.which) {  
                case 38:    
                    downUp("up");
                    break;
        // Extra code
            }
        });
    },
    templateUrl: 'public/templates/displayVolumeModal.html'
};  

Aucun commentaire:

Enregistrer un commentaire