angularjs ng-repeat with filter and track by $index 不起作用

angularjs ng-repeat with filter and track by $index not working

我正在尝试将一些视频(其名称位于此 json 文件中)放在一个 div 中,这是 json 文件:

{
    "videos": {
        "name": [
            "dfg.webm",
            "fdgh.mp4"
        ]
    }
}

这是脚本:

(function(){
    var app=angular.module("index",[]);

    var videoUrl=function(name){
        alert("asd");
        return "./videos/"+name;
    };  
    app.filter('videoUrl',function(){alert("asd");return videoUrl;});

    var mainController=function($scope,$http){
       var videosSuccess=function(response){
           $scope.videosJSON=response.data;         
       };
       var videosError=function(response){};
       $http({
           method: 'GET',
           url: "http://192.168.1.66/videos.json",
       }).then(videosSuccess,videosError);
    };
    app.controller("mainController",["$scope","$http",mainController]);

}());

这是 html:

<html lang="es" ng-app="index">
    <head>
    ...
    </head>
    <body ng-controller="mainController">
        <div id="videosdiv">
            <video ng-repeat="video in videosJSON.videos.name | filter:videoUrl track by $index" preload="metadata" ng-src="{{video}}" type="video/webm">      
            </video>
        </div>

    </body>
</html>

问题是浏览器正在呈现这个:

<video data-ng-repeat="video in videosJSON.videos.name | filter:videoUrl track by $index" preload="metadata" ng-src="dfg.webm" type="video/webm" class="ng-scope" src="dfg.webm">
</video>
<video data-ng-repeat="video in videosJSON.videos.name | filter:videoUrl track by $index" preload="metadata" ng-src="fdgh.mp4" type="video/webm" class="ng-scope" src="fdgh.mp4">      
</video>

而不是这个:

<video ng-repeat="video in videosJSON.videos.name track by $index" preload="metadata" ng-src="./videos/dfg.webm" type="video/webm" class="ng-scope" src="./videos/dfg.webm">      
</video>
<video ng-repeat="video in videosJSON.videos.name track by $index" controls="" preload="metadata" ng-src="./videos/fdgh.mp4" type="video/webm" class="ng-scope" src="./videos/fdgh.mp4">      
</video>

我认为过滤器未被使用,因为函数 "videoUrl" 内的警报未被触发,"ng-src" 或 "src" 属性也未被转换...有人可以告诉我发生了什么事或者我做错了什么?谢谢

那是因为你错误地使用了过滤器表达式。您将它用作 angular 内置 filterFilter 的表达式。相反,您想按原样使用过滤器,因为将它用作表达式需要修改原始数组(过滤器表达式函数中的第三个参数)。

改为:

 ng-repeat="video in videosJSON.videos.name | filter:videoUrl

 ng-repeat="video in videosJSON.videos.name | videoUrl 

做:-

   <video ng-repeat="video in videosJSON.videos.name | videoUrl track by $index" preload="metadata" ng-src="{{video}}" type="video/webm">      
   </video>

你的过滤器评估器应该是

var videoUrl=function(names){
    if(!angular.isArray(names)){ return []; }

    return names.map(function(name){
        return "./videos/"+name;
    });  
}

Plnkr with stub data

PS:因为这看起来更像是一个解析 url 的格式化过滤器,所以最好在控制器中使用它并更新 url视图模型本身而不是放置 DOM 过滤器(视图上的过滤器)会更昂贵。