将对象从数组模型传递到指令

时间:2014-03-10 07:24:33

标签: javascript angularjs angularjs-directive

我有一个包含带有源链接的图像的对象数组。我想在源链接死亡且无法加载图像时为每个图像添加标记。我有以下html代码和指令。

问题是我不能直接将图像对象传递给指令来设置它的属性。我已尝试向指令添加范围并通过参数传递但它不起作用,因此我以这种丑陋的方法结束了与外部范围的tighly耦合指令并对其进行处理(指令源片段中的注释行)。 / p>

问题是:是否可以通过将图像对象传递给指令而不使用手动$ 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
        });
    }
};

2 个答案:

答案 0 :(得分:0)

尝试:

.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"

答案 1 :(得分:0)

好吧,正如我所料,它是可行的(至少是那个更难看的问题),工作的朋友告诉我使用$ 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.
    });
  }
};
相关问题