【问题标题】:What is wrong with this AngularJS directive?这个 AngularJS 指令有什么问题?
【发布时间】:2016-02-27 23:48:18
【问题描述】:

我正在尝试为 AngularJS 编写一个 imgix 指令。这是我的代码:

MetronicApp
.directive('imgix', function() {
    return {
        replace: true,
        scope: {
            url: '='
        },
        restrict: "A",
        template: "<img class='thumbnail inline' width={{w}} height={{h}} src='https://mysite.imgix.net/{{url}}?h={{h}}&w={{w}}&fit=crop'>",
        link: function(scope, elm, attrs) {
            function ctrl(value, mode) {
                // check inputs
                if ((value === null) || (value === undefined) || (value === '')) {
                    // let's do nothing if the value comes in empty, null or undefined
                    return;
                }

                scope.h = attrs.height || 50;
                scope.w = attrs.width || 50;
                scope.url = value;


            }

            // by default the values will come in as undefined so we need to setup a
            // watch to notify us when the value changes
            scope.$watch(attrs.url, function(value) {
                ctrl(value, 'url');
            });
        }
    };
});

在 html 中,我有 2 张图片:

 <img imgix data-height="200" data-width="200" url="theme.options.homepageBackground" />

 <img imgix data-height="200" data-width="200" url="theme.options.menuBackground" />

但是结果和图片一样:

我不明白出了什么问题。范围有什么问题吗?

【问题讨论】:

  • 你的问题是什么?
  • 尽管两个图片的网址完全不同,但它们都显示相同的图片。
  • theme.options.homepageBackground 一个角度变量吗?如果是,您必须更改为{{ theme.options.homepageBackground }}
  • 它们是角度变量。但现在不显示图像。
  • 忘记我说的,我仔细检查过,它是错误的。你有正确的语法

标签: javascript angularjs angularjs-directive imgix


【解决方案1】:

我建议使用 ng-src 属性并将整个 url 从链接函数传递给指令。

【讨论】:

    【解决方案2】:

    您的指令范围绑定到父范围。请改用子作用域或隔离作用域。

    MetronicApp.directive('imgix', function() { return { scope: { url: '=' }

    【讨论】:

      【解决方案3】:

      我通过 Matthias 和 Julien 的组合解决了这个问题

      首先,我在指令中添加了大括号:

      <imgix data-height="200" data-width="200" url="{{theme.options.menuBackground}}" />
      

      然后我将 scope: {} 添加到指令代码中

      我看到手表代码中的值返回未定义。我改变了:

      scope.$watch(attrs.url, function(value) {
                      ctrl(attrs.url, 'url');
                  });
      

      现在可以了。谢谢。

      【讨论】:

        猜你喜欢
        • 2014-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-08
        • 2018-01-25
        • 2021-05-25
        • 1970-01-01
        相关资源
        最近更新 更多