javascript - ng-repeat 指令不起作用

标签 javascript angularjs

我有这个指令:

.directive('img', function () {
    return {
        restrict: 'E',
        link: function (scope, elem, attr) {
            if (attr.src && attr.type === "extension"){

                var url = "chrome-extension://" + chrome.runtime.id + attr.src
                // console.log(url)

                elem[0].removeAttribute('src')
                // elem[0].setAttribute("src", url)
                // elem[0].dataset.ngSrc = url
                console.log(elem[0])
                console.log(elem[0].src)

            }

        }
    };
})

个人资料.html:

          <tr ng-repeat="integration in profile.integrations">
             <td>
                  <!-- <h3>{{integration.provider}}</h3> -->
                 <img type="extension" src="/images/icons/{{integration.provider}}.png" alt="" width="50px">
             </td>
         </tr>

我的控制台日志仍然显示 src,并且不会删除它也不会替换它。这与 ng-repeat 有关,因为这可以完美地应用于另一张图像。

最佳答案

您基本上是在重新创建 Angular 的便利指令之一,该指令是针对在 src 属性中使用表达式的情况而制作的。使用 ng-src 而不是 src,您将不需要 img 指令

ng-src doc: https://docs.angularjs.org/api/ng/directive/ngSrc

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.

<img type="extension" 
     ng-src="/images/icons/{{integration.provider}}.png" alt="" width="50px">

正如 runTarm 在评论中指出的,这不会将 chrome-extension 协议(protocol)添加到图像 url,为此,您需要做两件事

  1. 将 chrome-extension 添加到 AngularJS 白名单中,否则 Angular 会在 URL 前面添加 unsafe:
  2. 将表达式添加到 ng-src 以添加协议(protocol)

添加到白名单

//modified from http://stackoverflow.com/a/15769779/560593
var app = angular.module( 'myApp', [] );
app.config( ['$compileProvider', function( $compileProvider ) {   
    //adds chrome-extension to the whitelist
    $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
]);
app.run(function($rootScope){
    //put the id on the rootScope so we can use it in expression
    $rootScope.extensionUrl = "chrome-extension://"+chrome.runtime.id;        
});

HTML

<img ng-src="{{extensionUrl}}/images/icons/{{integration.provider}}.png" alt="" width="50px">

JSFiddle

关于javascript - ng-repeat 指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969083/

相关文章:

javascript - 如何更改 vue-cli 的分隔符?

javascript - 为什么这不是 google.maps.Map 的 map 实例?无效值错误 : setMap: not an instance of Map;

javascript - AngularJs 值更改时隐藏输入的调用函数 $watch

javascript - 使用 AngularJS 将表单控件设置为未触及焦点

javascript - nvd3-angular 中的自定义饼图颜色

javascript - 动态创建的元素失去间距

javascript - Dexie:两个日期之间的事件

html - 下拉列表未使用 Angular js 中的选定值进行选择

javascript - 如何在 ng-view (angularjs) 中使用常规 javascript 代码

javascript - 如何抑制 asm.js 编译信息?