【问题标题】:Passing object from array model into directive将对象从数组模型传递到指令
【发布时间】:2016-01-10 20:59:31
【问题描述】:

我有一个对象数组,其中包含带有源链接的图像。当源链接失效且无法加载图像时,我想为每个图像添加标志。我有以下 html 代码和指令。

问题是我无法将图像对象直接传递给指令以在其上设置属性。我已经尝试将范围添加到指令并通过参数传递,但它不起作用,所以我以这种丑陋的方法结束,将指令与外部范围紧密耦合并处理它(指令源代码片段中的注释行)。

问题是:是否可以通过将图像对象传递给指令而不需要手动调用 $apply() 以更优雅的方式实现?可能是的,但我在周末尝试过但失败了。

<!-- AngularJS v. 1.0.8 -->
<ul>
  <li ng-repeat="image in images">
   <div>
      <img ng-src="{{image.srcLarge}}" fallback-src="/assets/fallback.png"/>
      <!--- image comments and other data -->
    </div>
  </li>
<ul>

指令:

.directive('fallbackSrc', function () {
var fallbackSrc = {
    restrict: 'A',
    link: function postLink(scope, iElement, iAttrs) {
        iElement.bind('error', function() {
            console.log("directive");
            angular.element(this).attr("src", iAttrs.fallbackSrc);
            scope.image.errorPresent = true; // this is problematic
            scope.$apply(); // this is also problematic
        });
    }
};

【问题讨论】:

  • 好的,所以我看到这个问题的表述不够清楚,所以回顾一下:我怎样才能以更优雅的方式创建这个指令,所以它不依赖于 scope.image,而是可以使用作为属性传递的图像对象吗?

标签: javascript angularjs angularjs-directive


【解决方案1】:

试试:

.directive('fallbackSrc', function() {
    return {
        restrict: 'A',
        link: function(scope,element,attrs){
            element.on('load', function() {
                 //loaded           
            });
            element.on('error', function() {
                        element.attr('src',attrs.fallbackSrc);
            });
            scope.$watch('ngSrc', function() {
                 //start      
            });      
       }
    }
})

试试:

ng-repeat="image in images" ng-init="image.errorPresent = false"

【讨论】:

  • 我认为我们在这个问题上意见不一。请在原始问题下方查看我的评论。
  • 好的,但是在 jquery real afaik 中没有其他方法可以使用 $apply
【解决方案2】:

好的,正如我所料,这是可行的(至少是那个更丑陋的问题),工作的朋友告诉我使用 $eval:

<img ng-src="{{image.srcLarge}}" fallback-src="/assets/fallback.png" imagemodel="image"/>

.directive('fallbackSrc', function () {
  var fallbackSrc = {
  restrict: 'A',
  link: function postLink(scope, iElement, iAttrs) {
    iElement.bind('error', function() {
        console.log("directive");
        angular.element(this).attr("src", iAttrs.fallbackSrc);
        var target = scope.$eval(iAttrs.modify);
        target.errorPresent = true; // no longer problematic after $eval call 
        scope.$apply(); // This must be done this way as we are modifying Angular model from the outside of AngularJS scope.
    });
  }
};

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2023-03-19
    相关资源
    最近更新 更多