【问题标题】:Passing scope parameters to a Custom Directive as ng-src is being called repeatedly将范围参数传递给自定义指令,因为 ng-src 被重复调用
【发布时间】:2016-12-01 01:38:10
【问题描述】:

我当前的实现如下所示,它正在工作,但由于 getImage 方法在表达式内部,当任何文本更改或在页面上输入数据时,它会被重复调用

HTML

        <div ng-repeat="product in pageData.products">
           <div>
            <img style="width:60px;" ng-src={{getImage(product)}} />
          </div>              
        </div>

JS:

    $scope.getImage = function(product)
{
       var image = Utils.getLocalStorageEntityByIdFromList(product.ID,"ProductID", "images");
       if(image) return image.Data;
        else return "";
};

我正在尝试将 getImage 方法放在 .directive 中,因为大多数帖子都建议并将产品作为参数传递到指令中。 发布链接 How to call a function in "ng-src"

我是 AngularJS 的新手,如果有任何帮助将 getImage 方法放入可以传递产品参数的指令中,我将非常感激。

如下所示。

JS:

 angular.module('MyApp', [])
    .controller('Ctrl2', function($scope) {
    })
    .directive('mySrc', function() {
        return {
        restrict: 'A',
        link: function ( scope, elem, attrs ) {
             var image = Utils.getLocalStorageEntityByIdFromList(product.ID,"ProductID", "images");
             elem.attr('src', image.Data);
        }
      };
    });

HTML:

<div ng-app="MyApp">
  <div ng-controller="Ctrl2">
   <div ng-repeat="product in pageData.products">
     <div><img my-src="product" /><div>      
   </div>
</div>

非常感谢您的宝贵时间。

【问题讨论】:

  • 使用此方法更新您的帖子并 getLocalStorageEntityByIdFromList 通知我
  • 您好 Aravid,感谢您的调查。对不起,我不明白你的意思,带有 .directive 的第二段 JS 代码目前无法正常工作,这就是我不确定的......

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat


【解决方案1】:

为避免多次调用 AngularJS 表达式中的函数,请使用 one-time binding:

<div ng-repeat="product in pageData.products">
   <div>
    <!-- REPLACE This
    <img style="width:60px;" ng-src={{getImage(product)}} />
    -->
    <!-- WITH One time binding -->
    <img style="width:60px;" ng-src={{::getImage(product)}} />
  </div>              
</div>

一次性绑定在ng-repeat 内容中特别有用,因为它们显着减少了活动观察者的数量。

来自文档:

一次性绑定

以:: 开头的表达式被视为一次性表达式。一次性表达式一旦稳定就会停止重新计算,如果表达式结果是一个未定义的值,这会在第一次摘要之后发生(参见下面的值稳定算法)。

-- AngularJS Developer Guide -- Expressions -- One-time Binding

【讨论】:

  • 非常感谢 georgeawg,一次性绑定非常适合我。
【解决方案2】:

ng-src 实际上使用 attr.$observe。在您的具体情况下,这可能不是必需的。

似乎可以只传递产品 ID,因为这就是用于获取图像 URL 的全部内容。我可能会尝试以下作为您的自定义指令的起点。

HTML

<div><img my-src="product.ID" /><div>  

JS

//in your new custom directive my-src
scope : {id:'=mySrc'},
link: function ( scope, elem, attrs ) {
    var image = Utils.getLocalStorageEntityByIdFromList(scope.id,"ProductID", "images");
    attrs.$set('src',image.Data);
}

【讨论】:

  • 感谢以上回答,这正是我所需要的,但我还没有尝试过,因为一次性绑定解决方案对我有用。非常感谢您的宝贵时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
相关资源
最近更新 更多