Search code examples
javascriptjqueryangularjsangularjs-directiveangular-directive

Not able to change attribute in $templateCache using an AngularJS Directive


This is my Directive :

module.directive('iconSwitcher', function() {

return {
    restrict : 'A',

    link : function(scope, elem, attrs) {

        var currentState = true;

        elem.on('click', function() {
            console.log('You clicked me!');

            if(currentState === true) {
                console.log('It is on!');
                angular.element(elem).removeAttr(attrs.src);
                angular.element(elem).attr(attrs.src, "../images/First.png");

            } else {
                console.log('It is off!');
                angular.element(elem).removeAttr(attrs.src);
                angular.element(elem).attr(attrs.src, "../images/Second.png");

            }

            currentState = !currentState

        });
    }
};
});

My aim is onClick I change the image source to another one. Normally it should work on html, But I don't know why it's not working when it comes to templateCache HTML. It must be something related to Directives and templateCache in AngularJS but I am new in this field and I don't have enough experience I guess.

    $templateCache.put('timeline_cursor.tpl.html', '<div icon-switcher><img style=" margin-bottom:6px;cursor:pointer;" src="../images/First.png" "/></div>');

Solution

  • The problems lie inside your iconSwitcher directives :

    1. jqLite function removeAttr and attr does not recognize your attribute name - ie. attrs.src and it will throw Error. You must change your attribute into src :

      elem.removeAttr('src', 'your/image/path');
      elem.attr('src', your/image/path);
      
    2. The position of your iconSwitcher directive inside your $templateCache and the way you call your element inside your iconSwitcher has conflict. Because in your $templateCache you put the icon-switcher attribute in the div instead in img tag, the elem inside your directive will be bound the the whole div inside $templateCache instead of img. You can work around this by either put the iconSwicher in the img tag or find img element by using jqLite find inside link:

      var img = elem.find('img');
      

      And change the src attribute of img instead of elem.

    Working fiddle for your reference.