【问题标题】:Change element width inside AngularJS directive更改 AngularJS 指令中的元素宽度
【发布时间】:2015-08-21 14:34:34
【问题描述】:

我的指令链接中有这样的代码:

        scope.parentWidth = function (){
            return{'width':element.parent().width()}
        }


        scope.$watch(scope.parentWidth, function(oldValue, newValue) {
            if (oldValue !== newValue) {
                element.css('width', newValue);
                console.log(element.width());
            }
        }, true);

但在控制台中,我看到宽度每次都是相同的(元素是一个简单的 div)。即使newValue 改变了。我做错了吗?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:
    scope.$watch('parentWidth', function(oldValue, newValue) {
                if (oldValue !== newValue) {
                    element.css('width', newValue +'px');
                    console.log(element.width());
                }
            }, true);
    

    查看作用域的属性时,只需将其作为字符串提供,否则第一个参数也可以是简单的幂等函数

    scope.$watch(function(){return scope.parentWidth;}, function(oldValue, newValue) {
                if (oldValue !== newValue) {
                    element.css('width', newValue +'px');
                    console.log(element.width());
                }
            }, true);
    

    【讨论】:

    • 其实,如果有问题也没关系。 parenWidth变化正常,但是element每次的宽度都是一样的,所以element.css('width', newValue);不设置元素的宽度。
    • 试一试 +'px' 有时这在尝试设置样式时很重要>
    • 是的,我有日志,但宽度是一样的。
    猜你喜欢
    • 1970-01-01
    • 2015-03-09
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多