更改属性';指令angularjs中的s值

更改属性';指令angularjs中的s值,angularjs,angularjs-directive,Angularjs,Angularjs Directive,当src属性的值为空时,我为图像标记生成一个指令,然后用默认值更改src值。 .directive('defaultImage', function($compile) { return { restrict : 'A', compile : function compile(tElement, tAttributes) { return { pre : function preLink(scope, element, attribute

当src属性的值为空时,我为图像标记生成一个指令,然后用默认值更改src值。

.directive('defaultImage', function($compile) {
return {
    restrict : 'A',
    compile : function compile(tElement, tAttributes) {

        return {
            pre : function preLink(scope, element, attributes) {
            },
            post : function postLink(scope, element, attrs) {
                if (attrs.src == undefined || attrs.src.length == 0) {
                    element.attr('src', '/delegate/resource/admin/images/default.png');
                    $compile(element)(scope);
                }
            }
        };
    }
}
});
用法:

<img src="{{entity.image}}" style="margin-left: 20px"
     height="120px" width="140px" default-image>


但这不起作用

首先,您是否熟悉
ng src
?它用于插入src表达式,以避免浏览器试图从
“path/to/{{url}}”而不是实际url(例如
“/path/to/image1.png”
)获取。如果
url
undefined
,它也不会加载图像

其次,
$compile(element)(scope)
是完全不必要的(事实上是不正确的)-如果没有其他内容,那么您就是在不必要地重新编译
defaultImage
指令

编辑:

嗯。。。这是我“过度思考”的一个例子。。。到目前为止,实现默认URL的最简单方法如下(无需任何指令):

原始答案:

那么,让我们看看
ngSrc
如何处理“good”案例,并为默认案例创建类似的内容。以下是来自以下站点的简化代码片段:

因此,使用类似的方法:

.directive("defaultImage", function(){
  return {
    link: function(scope, element, attr){

      // what Angular uses 
      // https://github.com/angular/angular.js/blob/v1.4.5/src/Angular.js#L191
      var msie = document.documentMode;

      var defaultImageUrl = "/path/to/default.png";

      attr.$observe("ngSrc", function(value){
         if (!value){
           attr.$set("src", defaultImageUrl);
           if (msie) element.prop("src", attr["src"]);
         }
      })
    }
  }
})

已测试。代码运行良好。展示你如何使用它。嗨,在我看来,你在指令中写的逻辑应该在你检索图像源的地方完成。
<img ng-src="{{entity.image || defaultUrl}}">
link: function(scope, element, attr){

  attr.$observe("ngSrc", function(value) {
    if (!value) {
      return;
    }

    attr.$set("src", value);

    // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
    // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
    // to set the property as well to achieve the desired effect.
    // we use attr[attrName] value since $set can sanitize the url.
    if (msie) element.prop("src", attr["src"]);
  });
}
.directive("defaultImage", function(){
  return {
    link: function(scope, element, attr){

      // what Angular uses 
      // https://github.com/angular/angular.js/blob/v1.4.5/src/Angular.js#L191
      var msie = document.documentMode;

      var defaultImageUrl = "/path/to/default.png";

      attr.$observe("ngSrc", function(value){
         if (!value){
           attr.$set("src", defaultImageUrl);
           if (msie) element.prop("src", attr["src"]);
         }
      })
    }
  }
})