【问题标题】:Not able to change attribute in $templateCache using an AngularJS Directive无法使用 AngularJS 指令更改 $templateCache 中的属性
【发布时间】:2015-06-23 02:27:06
【问题描述】:

这是我的指令:

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

        });
    }
};
});

我的目标是 onClick 我将图像源更改为另一个。通常它应该在 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>');

【问题讨论】:

    标签: javascript jquery angularjs angularjs-directive angular-directive


    【解决方案1】:

    问题在于您的iconSwitcher 指令:

    1. jqLite 函数 removeAttrattr 无法识别您的属性名称 - 即。 attrs.src 它将是throw Error。您必须将您的属性更改为 src

      elem.removeAttr('src', 'your/image/path');
      elem.attr('src', your/image/path);
      
    2. iconSwitcher 指令在 $templateCache 中的位置与您在 iconSwitcher 中调用元素的方式存在冲突。因为在您的$templateCache 中,您将icon-switcher 属性放在div 中而不是img 标记中,所以您的指令内的elem 将绑定整个div$templateCache 而不是img .您可以通过将iconSwicher 放入img 标记或使用jqLite findlink 中找到img 元素来解决此问题:

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

      并更改imgsrc 属性而不是elem

    Working fiddle 供您参考。

    【讨论】:

    • +1 非常感谢,我开始更改我的整个代码,因为我没有得到答案。谢谢它的工作,我很感激你的解释。我现在明白它是如何工作的。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2013-05-14
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多