我有这个指令:
.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,为此,您需要做两件事
- 将 chrome-extension 添加到 AngularJS 白名单中,否则 Angular 会在 URL 前面添加 unsafe:
- 将表达式添加到 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">
关于javascript - ng-repeat 指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969083/