Angular img src控制台错误

Vuc*_*cko 15 javascript angularjs

我正在使用ng-repeat打印所需文件夹中的所有图像,这些图像都在,<a>因为我正在使用fancyBox.

这是控制器的一个例子:

var ParentCtrl = function ($scope) {
    $scope.getTimes=function(n){ // for the ng-repeat
        return new Array(n);
    }; 
};

app.controller('projectController', ['$scope','$injector', function($scope, $injector) {
    $injector.invoke(ParentCtrl, this, {$scope: $scope});

    $scope.title = 'project';
    $scope.image_url = 'img/project/';
    $scope.image_num = 14; //image count -> [0.jpg, 1.jpg, 2.jpg, ..., 13.jpg]
}]);
Run Code Online (Sandbox Code Playgroud)

和模板:

<a href="" class="fancybox" rel="project-gallery"
    data-ng-repeat="t in getTimes(image_num) track by $index" 
    data-ng-href="{{image_url+($index)+'.jpg'}}">
        <img src="{{image_url+($index)+'.jpg'}}">
</a>
Run Code Online (Sandbox Code Playgroud)

这段代码工作正常,它显示了所有14个图像.但是,我在控制台中收到此错误:

GET http://localhost/projects/project-name/%7B%7Bimage_url+($index)+'.jpg'%7D%7D 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)

如何解决这个错误?

Kub*_*oda 20

这就是你要找的东西:https://docs.angularjs.org/api/ng/directive/ngSrc 这是因为浏览器尝试用src你提供的图像来获取.如果使用ng-src,angular将负责等待表达式编译,然后追加src<img>元素.

  • 嗯,这对我很愚蠢,我忘了`ng-src`.我还在学习角度所以我可以"负担得起"来犯这些错误:D干杯:) (3认同)

Kol*_*ban 6

在您的模板中,请使用data-ng-src而不是src.您的新模板将成为

<a href="" class="fancybox" rel="project-gallery"
    data-ng-repeat="t in getTimes(image_num) track by $index" 
    data-ng-href="{{image_url+($index)+'.jpg'}}">
        <img data-ng-src="{{image_url+($index)+'.jpg'}}">
</a>
Run Code Online (Sandbox Code Playgroud)

看到

https://docs.angularjs.org/api/ng/directive/ngSrc