javascript - 当 ng-src 被重复调用时,将范围参数传递给自定义指令

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

我当前的实现如下所示,它正在工作,但由于 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>

非常感谢您抽出时间。

最佳答案

为了避免多次调用 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>

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

来自文档:

One-time binding

An expression that starts with :: is considered a one-time expression. One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value (see value stabilization algorithm below).

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

关于javascript - 当 ng-src 被重复调用时,将范围参数传递给自定义指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40889266/

相关文章:

javascript:递归匿名函数?

javascript - Jquery 可使用自己的元素进行排序和删除

html - 使用 CSS/Angular JS 固定列和标题

javascript - 定义隔离范围时指令行为发生变化

javascript - 这个新的重复拖放指令有什么问题?

javascript - 将 key 添加到哈希中

javascript - js 或 CSS 不工作

javascript - 页面加载时的 AngularJS 1.2 ng-repeat 动画

angularjs - 如何从angularjs函数调用grails Controller

angularjs - angular.js广播错误: $rootScope.广播不是函数