无法使用AngularJS指令更改$ templateCache中的属性

时间:2015-04-16 15:06:39

标签: javascript jquery angularjs angularjs-directive angular-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

        });
    }
};
});

我的目标是点击我将图像源更改为另一个。通常它应该适用于html,但我不知道为什么它在templateCache HTML上不起作用。 它必须是与AngularJS中的Directives和templateCache相关的东西,但我是这个领域的新手,我猜想我没有足够的经验。

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

1 个答案:

答案 0 :(得分:1)

问题出在你的iconSwitcher指令中:

  1. jqLite函数removeAttrattr无法识别您的属性名称 - 即。 attrs.src throw Errorsrc。您必须将属性更改为elem.removeAttr('src', 'your/image/path'); elem.attr('src', your/image/path);

    iconSwitcher
  2. $templateCache指令在iconSwitcher内的位置以及您在$templateCache内调用元素的方式存在冲突。因为在icon-switcher中,您将div属性放在img而不是elem标记中,指令中的div将绑定整个$templateCache img 1}}在iconSwicher内而不是img。您可以通过在img标记中添加jqLite find或使用link内的var img = elem.find('img'); 找到src元素来解决此问题:

    img

    并更改elem的{​​{1}}属性,而不是{{1}}。

  3. Working fiddle供您参考。